父子之间通信
父传子
·创建传递条件
父组件.wxml中
<view >父组件中count:{{count}}</view>
//1、 my-test5是子组件
//2、 bind:事件名称="方法名字"
//3、 my-test5的count等待父组件传值
<my-test5 count="{{count}}"/>
父组件.js中
data: {
count:0
},
子组件.wxml中
<view>子组件中 count:{{count}}</view>
// button让子组件的count+1
<button bindtap="addCount">+1</button>
子组件.js 子组件接收父亲的count
// 子组件中声明这个count类型
properties: {
count:Number
},
// 此时已经接收了父组件定义的并穿过来的count 可以在子组件.wxml中使用
![image.png](https://img-blog.csdnimg.cn/img_convert/f5b5b34861c1f964f51825c6d4bee109.png#averageHue=#262c32&clientId=uc97424ef-511b-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=298&id=u048c870d&margin=[object Object]&name=image.png&originHeight=298&originWidth=300&originalType=binary&ratio=1&rotation=0&showTitle=false&size=12375&status=done&style=none&taskId=u20910bed-b99d-4b45-b4ca-bc13664a1c1&title=&width=300)
子组件.js文件 methods中定义方法
// 让子组件count自增加1
methods:{
addCount(){
this.setData({
count:this.properties.count+1
})
}
}
子传父
父传子已经实现,子组件my-test5中获得了count的值,此时我们点击button使count自增加1并让父组件同时渲染子传来的count
// bind:事件名=“方法”
// 目的让其父子互相绑定
<my-test5 count="{{count}}" bind:sync="syncCount"/>
然后就要在父组件.js中写这个 syncCount 方法
// 与data平级
// 此时父子件的方法就传递给了子组件 自增加1的同时 sync事件就会触发
syncCount(e){
// 用形参e来接收
console.log(e)
this.setData({
// 打印出e的时候 可以看出子组件传来的值就保存在detail的value中
// 所以直接调用重新赋值给count即可
count:e.detail.value
})
},
既然是在button方法自增加一的时候触发sync传给父亲,那么我们就来到子组件.js的addCount方法下
// 触发自定义事件sync 把数值同步给父组件 value就是传过去的值
this.triggerEvent('sync',{value:this.properties.count})
完成父子间通信全部代码
父组件.wxml
<my-test5 count="{{count}}" bind:sync="syncCount"/>
<view >父组件中count:{{count}}</view>
子组件.wxml
<view>子组件中 count:{{count}}</view>
<button bindtap="addCount">+1</button>
父组件.js
data: {
count:0
},
syncCount(e){
this.setData({
count:e.detail.value
})
},
子组件.js
properties: {
count:Number
},
methods: {
addCount(){
this.setData({
count:this.properties.count+1
})
this.triggerEvent('sync',{value:this.properties.count})
}
}