需求: 在一个项目中我们会发现有很多的共同样式 ;所以我们如果想优化代码就得自己封装组件:
子组件:
在根目录上建立一个components的文件夹,在里面自定义一个文件如:infocell
index.json
{
"component": true,//是否使用组件
"usingComponents": {}//引入组件,这里做为子组件为父组件使用,暂时不需要引入其它子组件,所以可以不写
}
index.wxml
<view class='payWrap'>
<text class='title'>{{title}}</text>
<text class='desc'>{{desc}}</text>
<text class='icon' bindtap='popView'>...</text>
</view>
index.js
// components/infocell/index.js
Component({
/**
* 组件的属性列表
*/
properties: {
// 左侧标题
title: { // 属性名
type: String, // 类型(必填),目前接受的类型包括:String, Number, Boolean, Object, Array, null(表示任意类型)
value: '' // 属性初始值(可选),如果未指定则会根据类型选择一个
},
desc: {
type: String,
value: ''
}
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
popView: function () {
// 注册点击事件传给父组件
this.triggerEvent('popView')
}
}
})
父组件引入infocell子组件:
detail文件下的index.json
{
"usingComponents": {
//infocell为自定义命名,冒号后为子组件的路径
"infocell": "/components/infocell/index",
}
}
detail文件下的index.wxml
标签为json中自定义的属性名
bind:popView的点击事件为Infocell传递过来的点击事件名(popView)绑定的popView要和子组件一样
<infocell title='支付' desc='{{baitiaoSelectItem.desc}}' bind:popView='popBaitiaoView'></infocell>
detail文件下的index.js
给组件赋值:
Page({
/**
* 页面的初始数据
*/
data: {
hideBaitiao: true, // 是否隐藏白条的遮罩
baitiaoSelectItem: {
desc: "【白条支付】首单享立减优惠"
},
},
/**
* 显示白条弹框
使用子组件传递过来的事件
*/
popBaitiaoView: function () {
this.setData({
hideBaitiao: false
})
},
})