小程序父子組件傳值

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)。

myEventDetailmyEventOption都是對象,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
        })
    }
})
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容