1.父傳子
父組件組件傳遞子組件通過屬性傳值,例如tranBool="{{Bool}}"的形式將變量Bool傳遞給子組件,如果不傳變量的話可以不用加花括號。
父組件
//wxml
<view>
<childComponent
tranBool="{{Bool}}"
tranString="hello world"/>
</view>
//js
Page({
data: {
Bool:false
}
})
子組件
子組件獲取properties里的值可以在組件生命周期的attached或者 ready通過this.data.來訪問。
//wxml
<view>
<view>{{tranBool}}</view>
<view>{{tranString}}</view>
</view>
//js
Component({
properties: {
tranBool: {
type: Boolean,
value: true
},
tranString: {
type: String,
value: ''
}
//tranBool: Boolean, // 簡化的定義方式
//tranString: Boolean // 簡化的定義方式
},
lifetimes: {
attached() {
// 在組件實例進入頁面節(jié)點樹時執(zhí)行
console.log(this.data.tranBool)
console.log(this.data.tranString)
},
ready() {
// 在組件在視圖層布局完成后執(zhí)行
console.log(this.data.tranBool)
console.log(this.data.tranString)
}
}
})
2.子傳父(triggerEvent)
triggerEvent方法可以把組件內部的數據傳到外面,觸發(fā)組件外的事件。它接收3個參數:
this.triggerEvent('myevent', myEventDetail, myEventOption)。
myEventDetail和myEventOption都是對象,myEventDetail是傳到組件外的數據,myEventOption有三個參數可以設置:
- bubbles 默認false 事件是否冒泡
- composed 默認false 事件是否可以穿越組件邊界
- capturePhase 默認false 事件是否擁有捕獲階段
子組件
//wxml
<view>
<view bindtap="changeStatus">點擊我傳遞父組件</view>
</view>
//js
Component({
properties: {
tranBool: {
type: Boolean,
value: true
}
},
methods:{
changeStatus(){
this.triggerEvent('myevent', this.data.tranBool)
}
}
})
父組件
//wxml
<view>
<childComponent
tranBool="{{Bool}}"
bind:myevent="changeStatus" />
</view>
//js
Page({
data: {
Bool: false
},
changeStatus(val) {
this.setData({
Bool: !val.detail
})
}
})