一、小標題1:從父組件向子組件傳值
在微信小程序中,子組件的屬性需要從父組件傳遞。在父組件中定義一個變數,將它通過屬性傳遞給子組件,即可完成傳值。
<!-- 在父組件中 -->
<custom-component value="{{parentValue}}"/>
<!-- 在子組件中 -->
<view>{{value}}</view>
Component({
properties: {
value: {
type: String,
value: ''
}
}
})
在上述代碼中,父組件傳遞了一個變數parentValue給子組件,子組件通過properties接收該值,並渲染在view中。
二、小標題2:從子組件向父組件傳值
在微信小程序中,由子組件向父組件傳遞數據相對複雜,需要使用triggerEvent方法。在子組件中定義一個函數,當觸發該函數時,通過triggerEvent調用父組件的事件方法,將數據一起傳遞給父組件。
<!-- 在父組件中 -->
<custom-component bind:childEvent="childEventHandler" />
<!-- 在子組件中 -->
<button bindtap="tapHandler">傳遞數據</button>
Component({
methods: {
tapHandler: function() {
this.triggerEvent('childEvent', {childValue: '我是子組件傳遞的值'});
}
}
})
在上述代碼中,子組件通過button按鈕將childValue的值傳遞給childEvent事件,父組件調用childEventHandler方法,接收該值並使用。
三、小標題3:依賴注入方式傳遞數據
除了以上兩種方式,也有依賴注入方式傳遞數據的處理方式。
在微信小程序中,可以使用開發者工具內置的behavior定義一些通用邏輯,例如獲取用戶信息等,然後讓一些相關組件引用它。在這裡也可以使用behavior傳遞數據。
// 定義behavior
module.exports = Behavior({
behaviors: [],
properties: {
value: {
type: String,
value: ''
}
}
})
// 定義組件
<!-- 在父組件中 -->
<custom-component value="{{parentValue}}"/>
<!-- 在子組件中 -->
<view>{{value}}</view>
Component({
behaviors: [require('path/to/behavior')],
properties: {
value: {
type: String,
value: ''
}
}
})
在上述代碼中,子組件引用了behavior,該behavior的properties中定義了value屬性,子組件也定義了value屬性,這樣當子組件引用該behavior時,自身的value屬性將被修改。
四、小標題4:slot插槽傳遞數據
微信小程序中,使用slot插槽時,可以在插槽中傳遞數據。
<!-- 在父組件中 -->
<custom-component>
<template slot="slotName">
{{parentValue}}
</template>
</custom-component>
<!-- 在子組件中 -->
<slot name="slotName"></slot>
在上述代碼中,父組件通過template在custom-component組件中定義了一個名為slotName的插槽,並在其中傳遞了一個parentValue值,在子組件中通過slot引用該插槽即可。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/227376.html