自定义组件有自已的作用域,可以使用组件通信完成 父子组件之间的数据传递。
父传子
1.父组件通过属性赋值为子组件传递数组
<!-- 页面wxml中 -->
<view class="box">
<!-- 应用自定义组件header -->
<header isLogin="{{true}}" tips="{{msg}}" />
</view>
2.子组件通过properties节点接收父组件数据
// 组件js中
Component({
// 接收父组件数据
properties: {
isLogin: Boolean,
tips: {
// 属性的数据类型
type: String,
// 属性的默认值
value: 'hello'
}
},
methods:{
// 子组件可以直接修改父组件传递的数据,不会影响修改到父组件
// 没有单向数据流限制
setTips(){
this.setData({
tips:'hello world'
})
}
}
})
注意:子组件可以直接修改父组件传递的数据,不会影响修改到父组件,没有单向数据流限制
3.查看或调试传入组件的数据与页面数据的查看方式不同,具体查看如下图所示:
说明:选中要查看的组件,通过右侧componentData面板查看
![](https://i-blog.csdnimg.cn/blog_migrate/6b304e05beade9d4255d1a8d063dba2d.png)
子传父
1.父组件在子组件上绑定自定义事件,提供自定义事件回调方法
在自定义事件回调方法中,通过默认形参event.detail获取数据
<!-- 页面wxml中 -->
<!-- 应用自定义组件 -->
<header isLogin="{{true}}" tips="{{msg}}"
+ bind:事件名="mycallback" />
// 页面js中
Page({
// 父组件中的数据
data: {
msg:"你好!"
},
// 自定义事件的回调
+ mycallback: function (e) {
+ console.log('我是父组件中的回调函数...',e.detail);
+ }
})
2.子组件触发父组件自定义事件
通过this.triggerEvent('自定义事件名称',data)触发和传递数据,【 类似Vue中的 $emit( ) 】
// 组件js中
Component({
methods: {
sayHi: function () {
// 并且将 {name: '小明', age: 18} 做为参数,传给父组件自定义事件的回调函数
+ this.triggerEvent('事件名', {name: '小明', age: 18});
}
}
})