properties 父传子
组件的对外属性,主要用来接收组件使用者传递给组件内部的属性以及数据。类似于vue的props。
properties
内可以直接使用observer
监听数据变化,并只监听改变了的状态。
(外层的observer
只要setData就会被监听到,不管值是否发生改变)
<customCheckbox label="{{label}}" id="customCheckbox" />
<button bindtap="onClickCusCheckbox"></button>
onClickCusCheckbox() {this.setData({label: "改变label"});}
<text>{{label || 我是标签}}</text>
Component({
properties: {
label: String, // 简写
position: { // 全写
type: String, // 类型
value: 'left', // 默认值
// 可选:当属性值变化时触发的观察者函数
observer: function (newVal, oldVal) {
console.log('isChecked changed from', oldVal, 'to', newVal);
}
}
}
})
triggerEvent发射 bindmyEvent接收自定义事件 子传父
triggerEvent发射自定义事件,父组件内需要添加bind自定义事件名接收。类似于vue的emit。
- 子组件内
this.triggerEvent()
发射自定义事件 第一个参数事件名 第二个参数传递的值。 - 父组件内需要添加
bind自定义事件
,接收参数事件对象event.detail
里面包含组件传递的值。
<customBox bindmyEvent="CToFGetData" id="customBox">
CToFGetData(event){console.log(event.detail)}
<button type="primary" plain bindtap="onClickCtoF">子传父</button>
data: {num: 999988887777},
onClickCtoF() {this.triggerEvent('myEvent', this.data.num)},