wepy父子元件props傳值
阿新 • • 發佈:2018-12-03
WePY中父子元件之間傳值依靠props來實現,props物件中聲明瞭我們需要傳遞的值。傳值有兩種方式,包括靜態傳值和動態傳值。
靜態傳值
父元件向子元件傳遞常量資料,只能傳遞String字串型別。
在父元件template模板部分的元件標籤中,使用子元件props物件中所宣告的屬性名作為其屬性名來向子元件傳值。
父:
<child title="mytitle"></child>
子:
props = {
title: String
};
onLoad () {
console.log(this.title); // mytitle
}
動態傳值(一個變另外一個跟著變)
父---->子:父元件使用.sync修飾符
子---->父:設定子元件props的twoWay: true
父<—>子:既使用.sync修飾符,同時子元件props中新增的twoWay: true
// 父: <child :title="parentTitle" :syncTitle.sync="parentTitle" :twoWayTitle="parentTitle"></child> data = { parentTitle: 'p-title' }; // 子: props = { // 靜態傳值 title: String, // 父向子單向動態傳值 syncTitle: { type: String, default: 'null' }, twoWayTitle: { type: String, default: 'nothing', twoWay: true } }; onLoad () { console.log(this.title); // p-title console.log(this.syncTitle); // p-title console.log(this.twoWayTitle); // p-title this.title = 'c-title'; console.log(this.$parent.parentTitle); // p-title. this.twoWayTitle = 'two-way-title'; this.$apply(); console.log(this.$parent.parentTitle); // two-way-title. --- twoWay為true時,子元件props中的屬性值改變時,會同時改變父元件對應的值 this.$parent.parentTitle = 'p-title-changed'; this.$parent.$apply(); console.log(this.title); // 'c-title'; console.log(this.syncTitle); // 'p-title-changed' --- 有.sync修飾符的props屬性值,當在父元件中改變時,會同時改變子元件對應的值。 }