用于父组件向子组件的指定属性设置数据,只能传递普通类型的数据,无法将方法传递给子组件
用于子组件向父组件传递数据,可以传递任意数据
①在父组件的js中,定义一个函数,这个函数即将通过自定义事件的形式,传递给子组件
②在父组件的wxml中,通过自定义事件的形式,将步骤①中定义的函数引用,传递给子组件
③在子组件的js中,通过调用this.triggerEvent('自定义事件名称', {/*参数对象*/}),将数据发送到父组件
④在父组件的js中,通过e.detail获取到子组件传递过来的数据
父组件还可以通过this.selectComponent('id或class选择器') 获取子组件实例对象。直接访问子组件的任意数据和方法
组件对外开放属性
properties: {
count: Number
},
组件wxml
<view>子组件中count为:{{count}}view>
页面
页面js
data: {
count: 10
},
页面wxml
<view>父组件中的count为:{{count}}view>
<my-test5 count="{{count}}">my-test5> //通过组件的count属性将值传入
页面js
syncCount(e){ //此参数用于接收子组件传递过来的数据
console.log('syncCount'),
console.log(e) //输出子组件传递过来的值
this.setData({
count: e.detail.value //使用子组件的值
})
},
页面wxml
<view>父组件中的count为:{{count}}view>
<my-test5 count="{{count}}" bind:sync="syncCount">my-test5>
子组件js
methods: {
addCount(){
this.setData({
count: this.properties.count+1
}),
this.triggerEvent('sync',{value: this.properties.count}) //调用父组件传递过来的方法并传值
}
}
页面wxml
<view>父组件中的count为:{{count}}view>
<my-test5 count="{{count}}" bind:sync="syncCount" class="customA" id="cA">my-test5>
<button bindtap="getChild">获取子组件的实例对象button>
页面js
getChild(){
const child = this.selectComponent('#cA')
console.log(child)
child.setData({
count: child.properties.count+1
})
},