属性绑定
用于父组件向子组件的指定属性设置数据,仅能设置json兼容的数据
子组件
wxml:
<view>子组件的count值:{{count}}</view>
js
Component({
/**
* 组件的属性列表
*/
properties: {
count: Number
}
)}
父组件
wxml:
<test2 count="{{count}}"></test2>
<view>父组件的count值:{{count}}</view>
js
Page({
/**
* 页面的初始数据
*/
data: {
count: 1
}
)}
json
{
"usingComponents": {
"test2":"/components/test2/test2"
}
}
效果示例
事件绑定
用于子组件向父组件传递数据,可以传递任意数据
步骤:
- 在父组件的js中,定义一个函数,这个函数即将通过自定义事件的形式传递给子组件
- 在父组件wxml中,通过自定义事件的新年形式,将步骤1中定义的函数引用,传递个子组件
- 在子组件的js中,通过
this.triggerEvent
(‘自定义事件名称
’,{参数对象
}),将数据发送到父组件 - 在父组件的js中,通过
e.detail
获取到子组件传递过来的数据
子组件wxml:
<view>子组件的count值:{{count}}</view>
<button type="primary" bindtap="addCount">子组件的按钮:count+1</button>
子组件js
// components/test2.js
Component({
/**
* 组件的属性列表
*/
properties: {
count: Number
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
addCount() {
this.setData({
count: this.properties.count + 1
})
//触发事件,发送数据给父组件
this.triggerEvent("eventHandler",{value:this.properties.count})
}
}
})
父组件绑定事件 事件名称eventHandler
数据接收函数addCount
<test2 count="{{count}}" bind:eventHandler="addCount"></test2>
<view>父组件的count值:{{count}}</view>
效果示例
获取组件实例
父组件通过this.selectComponent('class或id选择器')
获取子组件实例的对象,这样可以直接访问子组件的任意数据和方法`
父组件
wxml:
<test2 count="{{count}}" bind:eventHandler="addCount" id="Child"></test2>
<view>父组件的count值:{{count}}</view>
<button type="primary" bindtap="getChild">获取子组件实例对象</button>
父组件js
getChild() {
const child = this.selectComponent("#Child")
child.setData({
count:child.properties.count+1//修改子组件的数据
})
//child.addCount()调用子组件的函数
},
子组件
wxml
<view>子组件的count值:{{count}}</view>
<button type="primary" bindtap="addCount">子组件的按钮:count+1</button>
js
methods: {
addCount() {
this.setData({
count: this.properties.count + 1
})
//触发事件,发送数据给父组件
this.triggerEvent("eventHandler",{value:this.properties.count})
}
}
效果示例