天天看點

小程式父子元件傳值

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() {
            // 在元件執行個體進入頁面節點樹時執行
            console.log(this.data.tranBool)
            console.log(this.data.tranString)
        },
        ready() {
            // 在元件在視圖層布局完成後執行
            console.log(this.data.tranBool)
            console.log(this.data.tranString)
        }
    }
})
           

2.子傳父(triggerEvent)

triggerEvent

方法可以把元件内部的資料傳到外面,觸發元件外的事件。它接收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
        })
    }
})