美文网首页uni-app
3.uni-app(自定义组件)

3.uni-app(自定义组件)

作者: Wang_Mr | 来源:发表于2020-05-20 16:41 被阅读0次

创建自定义组件

  1. 项目根目录新建components目录

2.右键components目录,新建组件
勾选创建同名目录,使用自定义组件的时候,不用import了

新建组件.png

3.设置自定义属性
自定义属性包含三项:名称,value的类型、默认值

<script>
    export default {
        props: {
            src: {
                type: String,
                default: ""
            },
            text: {
                type: String,
                default: ""
            }
        }
    }
</script>

4.使用自定义属性

// 大括号获取动态的value
<text class="find-textBlack">{{text}}</text>
// 属性替换动态的value  ①属性前要用:②动态value对应的属性名(不需要大括号)
<image :src="src" mode="aspectFit"></image>

5.脚本块获取自定义属性的value

var num = this.$props.属性名

6.0动态设置样式
:style="{'height':statusBarHeightPx}"
①动态样式要用:style=
②{} 大括号代表动态value
③大括号里的属性名要用''括起来
④大括号里的属性值(固定值)用''括起来 如下所示:box-sizing,position
④大括号里的属性值(变量)用data数据里的属性名 如下所示:background-color,height

data() {
    return {
        statusBarHeight: "",
        bg: "#2fa1f0"
    };
}

6.1方法动态设置样式
:style="getColor(params)"
①动态样式要用:style=
②""里面为调用的方法

getColor(params) {
     let str = '#FFFFFF'
     ...
     return {
        'background-color': str
     }
}

7.自定义组件发送事件给页面

// 参数1:自定义事件名
// 参数2:传递的数据
this.$emit("downCallback","下拉刷新")

8.页面调用自定义组件的方法

// 自定义组件
// ①定义方法
refreshEnd() {
    this.mescroll.endSuccess()
}

// 页面
// ①通过给自定义组件绑定ref
<Custom src="../../static/home-icon/find_qiuguan.png" text="球馆" ref="refresh" ></Custom >
// ②调用自定义组件方法
this.$refs.refresh.自定义组件方法名

// 示例:this.$refs.refresh.refreshEnd()

使用自定义组件

//  @downCallback='downRefresh' 
//  downCallback组件自定义事件名
//  downRefresh接收事件数据的方法

<view class="header">

    <Custom src="../../static/home-icon/find_qiuguan.png" text="球馆" oneRowItemNum="2" @downCallback='downRefresh' ></Custom >
    <Custom src="../../static/home-icon/cclub.png" text="俱乐部" oneRowItemNum="2" @downCallback='downRefresh'></Custom >

</view>

downRefresh(data) {
    // data 接收事件的数据 
},

相关文章

网友评论

    本文标题:3.uni-app(自定义组件)

    本文链接:https://www.haomeiwen.com/subject/xijnohtx.html