一、父組件向子組件傳值
即WXML 數據綁定:用於父組件向子組件的指定屬性設置數據,僅能設置 JSON 兼容數據(自基礎庫版本 2.0.9 開始,還可以在數據中包含函數)。具體請看https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/wxml-wxss.html
1、流程梳理:
父組件father
通過數據綁定的形式進行屬性設置(grade)與賦要傳的值(rank)。
<son grade="{{rank}}"></son>
子組件son
第一步:在properties中進行屬性名設置。properties爲組件的對外屬性,是屬性名到屬性設置的映射表。這樣我們就能映射到(找到)此處的grade~
properties:{
grade:{
type:Number
}
},
第二步:接下來可以使用grade了,使用與data中的數據是一樣的方式,即this.data.grade;只是data是組件的內部數據,properties是組件的對外屬性.它們都可用於組件的模板渲染!
說明:其實properties中的值也可以這樣訪問:this.properties.grade;
2、具體展示:
父組件:
father.wxml:
<view class="indexView">
<son grade="{{rank}}"></son>
</view>
father.js
Component({
data:{
rank:1,
}
})
father.json
{
"component": true,
"usingComponents": {
"son": "/pages/son/son"
}
}
子組件:
son.wxml
<view>子組件頁</view>
son.js
Component({
properties:{
grade:{
type:Number
}
},
ready: function () {
console.log("this.data.grade====",this.data.grade);
},
})
son.json
{
"component": true
}
二、子組件向父組件傳值
通過事件進行傳值,可以傳遞任意數據。自定義組件可以觸發任意的事件,引用組件的頁面可以監聽這些事件。
1、流程梳理
子組件father
綁定一個事件處理函數,然後通過triggerEvent觸發指定的事件!
this.triggerEvent("sendEvent", "我來自子組件"); // sendEvent自定義名稱事件
父組件son
第一步:在組件的引用處通過bind/catch綁定triggerEvent指定的事件名(sendEvent);
<son bindsendEvent="receiveValue"></son>
第二部:接收值
receiveValue:function(res){
console.log("接收子組件傳過來的值" + '....',res.detail)
}
2、代碼展示
son.wxml:
<view bindtap="sendMesgToFather">點我向父組件傳值</view>
son.js
Component({
methods:{
// 向父組件發送值
sendMesgToFather: function(){
this.triggerEvent("sendEvent", "我來自子組件"); // sendEvent自定義名稱事件
}
}
})
father.wxml
<view class="indexView">
<!-- bind+子組件中的自定義名稱事件sendEvent -->
<son bindsendEvent="receiveValue"></son>
</view>
father.js
Component({
methods:{
receiveValue:function(res){
console.log("接收子組件傳過來的值" + '....',res.detail)
}
}
})
最後打印的結果:接收子組件傳過來的值.... 我來自子組件
!!!重點說明:
1>由於子組件son是被引入的組件,所以它必須要註冊爲組件,但是父組件father不一定,把它改成page頁面,上面的邏輯也是適用的!不僅是傳值,調用方法也一樣,father是組件或普通頁面,具體見:https://blog.csdn.net/Syleapn/article/details/94591977
2>如果以上兩種方式不足以滿足需要,父組件還可以通過 this.selectComponent
方法獲取子組件實例對象,這樣就可以直接訪問子組件的任意數據(這個數據包括properties與data中的)和方法了。具體一個簡單的示例可以看這個,展示瞭如何使用~