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

创建自定义组件

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

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

新建组件.png

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

<script>
    export default {
        props: {
            src: {
                type: String,
                default: ""
            },
            text: {
                type: String,
                default: ""
            },
            border: {
                type: Number,
                default: 2
            },
            // Array类型默认值要以函数的形式进行返回
            data: {
                type: Array,
                default: () {
                    return []
                }
            }
        }
    }
</script>

4.使用自定义属性

// 组件内部使用 - 大括号获取调用者传值
<text class="find-textBlack">{{text}}</text>
// 调用者引用组件传值
<Custom text="abc"></Custom>
// 组件内部使用方式
<image :src="src"></image>
// 调用者使用变量传值时  ①属性前要用:②值为变量名(不需要大括号)
<Custom :src="imgUrl" ></Custom>
// 如:
data() {
    return {
        imgUrl:"http://www.xxx.xx/a.jpg"
    }
}
// 如果设置为接收Number类型 ,调用者传值直接为常量,
// 需要属性前加:否则认为传的是字符串2,而不是数字类型2
// Boolean类型同Number类型
// 当然如果值为变量,如上"src"使用方式一样
<Custom :border="2" ></Custom>

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
     }
}

6.2动态引用computed里的方法
:style="{'height':maxHeight}"
①动态样式要用:style=
②值为computed里的方法名

computed: {
    maxHeight() {
        return "calc(" + this.page.topBarHeight + " + 100px)"
    }
}

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()

9.class样式的穿透

// 内部组件禁止引用方穿透样式 用scoped进行修饰

<view class="code"></view>

<style lang="scss" scoped>
    .code {
        color: #FFFFFF;
    }
</style>

// 引用方穿透组件样式(前提 组件未使用scoped修饰)

<Custom class="new"></Custom >

.new >>> .code{
    color: #4CD964;
}
// 或
.new /deep/ .code{
    color: #4CD964;
}

使用自定义组件

//  @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 接收事件的数据 
},
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。