先看官方文档
组件间的基本通信方式有以下几种。
this.selectComponent
方法获取子组件实例对象,这样就可以直接访问组件的任意数据和方法。看官方示例
<!-- 页面的 json -->
{
"usingComponents": {
"my-component": "/components/custom-component"
}
}
<!-- 页面的 WXML -->
<my-component my-property="example" />
<my-component my-property="{{msg}}" />
<!-- 页面的 js -->
const app = getApp()
Page({
data: {
msg:'hello wechar'
},
onLoad: function () {
},
})
<!-- 组件 custom-component.wxml -->
<custom-component>
<view>{{myProperty}}</view>
<button bindtap='onMyButtonTap'>Button</button>
<view>{{A[0].B}}</view>
<button bindtap='_myPrivateMethod'>_myPrivateMethod</button>
</custom-component>
<!-- 组件 custom-component.json-->
Component({
behaviors: [],
properties: {
myProperty: { // 属性名
type: String, // 类型(必填),目前接受的类型包括:String, Number, Boolean, Object, Array, null(表示任意类型)
value: '', // 属性初始值(可选),如果未指定则会根据类型选择一个
observer: function (newVal, oldVal) { } // 属性被改变时执行的函数(可选),也可以写成在methods段中定义的方法名字符串, 如:'_propertyChange'
},
myProperty2: String // 简化的定义方式
},
data: {
A: [{
B: 'init data.A[0].B'
}]
}, // 私有数据,可用于模版渲染
lifetimes: {
// 生命周期函数,可以为函数,或一个在methods段中定义的方法名
attached: function () { },
moved: function () { },
detached: function () { },
},
// 生命周期函数,可以为函数,或一个在methods段中定义的方法名
attached: function () { }, // 此处attached的声明会被lifetimes字段中的声明覆盖
ready: function() { },
pageLifetimes: {
// 组件所在页面的生命周期函数
show: function () { },
},
methods: {
onMyButtonTap: function () {
this.setData({
// 更新属性和数据的方法与更新页面数据的方法类似
myProperty: 'Test',
'A[0].B':'hello world' //改变数组和对象的属性值有点不一样
})
},
_myPrivateMethod: function () {
// 内部方法建议以下划线开头
this.replaceDataOnPath(['A', 0, 'B'], 'myPrivateData') // 这里将 data.A[0].B 设为 'myPrivateData'
this.applyDataUpdates()
},
_propertyChange: function (newVal, oldVal) {
}
}
})
说明:页面通过my-property讲example字符串传递给自定义组件,同样也可以使用数据绑定的方法
image.png
代码示例同上,在子组件中的methods中定义方法,通过this.setData({})改变
methods: {
onMyButtonTap: function () {
this.setData({
// 更新属性和数据的方法与更新页面数据的方法类似
myProperty: 'Test',
'A[0].B':'hello world' //改变数组和对象的属性值有点不一样
})
},
}
<!-- index.wxml-->
<text>{{msg}}</text>
<my-component my-property="{{txt}}" bindmyevent='change'/>
<!-- index.js-->
const app = getApp()
Page({
data: {
msg:'hello wechar',
txt:'我们不一样'
},
onLoad: function () {
},
change:function(e){
console.log(e.detail);
this.setData({
msg:e.detail.val
})
}
})
<!-- 组件 custom-component.wxml -->
<custom-component>
<view>{{myProperty}}</view>
<button bindtap='onMyButtonTap'>Button</button>
<view>{{A[0].B}}</view>
<button bindtap='_myPrivateMethod'>_myPrivateMethod</button>
<button bindtap='changeParentData'>向父组件传值</button>
</custom-component>
<!-- 组件 custom-component.js -->
Component({
behaviors: [],
properties: {
myProperty: {
type: String,
value: ''
},
myProperty2: String // 简化的定义方式
},
data: {
}, // 私有数据,可用于模版渲染
...
methods: {
...
changeParentData:function(){
var myEventDetail = {
val:'您好'
} // detail对象,提供给事件监听函数
var myEventOption = {
} // 触发事件的选项
this.triggerEvent('myevent', myEventDetail, myEventOption);
//这样通过事件将参数 传递给被监听 函数 从而实现通信
}
}
})