組件間關(guān)系
定義和使用組件間關(guān)系
有時需要實現(xiàn)這樣的組件:
這個例子中, custom-ul 和 custom-li 都是自定義組件,它們有相互間的關(guān)系,相互間的通信往往比較復(fù)雜。此時在組件定義時加入 relations 定義段,可以解決這樣的問題。示例:
// path/to/custom-ul.js
Component({
relations: {
'./custom-li': {
type: 'child', // 關(guān)聯(lián)的目標節(jié)點應(yīng)為子節(jié)點
linked: function(target) {
// 每次有custom-li被插入時執(zhí)行,target是該節(jié)點實例對象,觸發(fā)在該節(jié)點attached生命周期之后
},
linkChanged: function(target) {
// 每次有custom-li被移動后執(zhí)行,target是該節(jié)點實例對象,觸發(fā)在該節(jié)點moved生命周期之后
},
unlinked: function(target) {
// 每次有custom-li被移除時執(zhí)行,target是該節(jié)點實例對象,觸發(fā)在該節(jié)點detached生命周期之后
}
}
},
methods: {
_getAllLi: function(){
// 使用getRelationNodes可以獲得nodes數(shù)組,包含所有已關(guān)聯(lián)的custom-li,且是有序的
var nodes = this.getRelationNodes('path/to/custom-li')
}
},
ready: function(){
this._getAllLi()
}
})
// path/to/custom-li.js
Component({
relations: {
'./custom-ul': {
type: 'parent', // 關(guān)聯(lián)的目標節(jié)點應(yīng)為父節(jié)點
linked: function(target) {
// 每次被插入到custom-ul時執(zhí)行,target是custom-ul節(jié)點實例對象,觸發(fā)在attached生命周期之后
},
linkChanged: function(target) {
// 每次被移動后執(zhí)行,target是custom-ul節(jié)點實例對象,觸發(fā)在moved生命周期之后
},
unlinked: function(target) {
// 每次被移除時執(zhí)行,target是custom-ul節(jié)點實例對象,觸發(fā)在detached生命周期之后
}
}
}
})
注意:必須在兩個組件定義中都加入relations定義,否則不會生效。
關(guān)聯(lián)一類組件
有時,需要關(guān)聯(lián)的是一類組件,如:
input
custom-form 組件想要關(guān)聯(lián) custom-input 和 custom-submit 兩個組件。此時,如果這兩個組件都有同一個behavior:
// path/to/custom-form-controls.js
module.exports = Behavior({
// ...
})
// path/to/custom-input.js
var customFormControls = require('./custom-form-controls')
Component({
behaviors: [customFormControls],
relations: {
'./custom-form': {
type: 'ancestor', // 關(guān)聯(lián)的目標節(jié)點應(yīng)為祖先節(jié)點
}
}
})
// path/to/custom-submit.js
var customFormControls = require('./custom-form-controls')
Component({
behaviors: [customFormControls],
relations: {
'./custom-form': {
type: 'ancestor', // 關(guān)聯(lián)的目標節(jié)點應(yīng)為祖先節(jié)點
}
}
})
則在 relations 關(guān)系定義中,可使用這個behavior來代替組件路徑作為關(guān)聯(lián)的目標節(jié)點:
// path/to/custom-form.js
var customFormControls = require('./custom-form-controls')
Component({
relations: {
'customFormControls': {
type: 'descendant', // 關(guān)聯(lián)的目標節(jié)點應(yīng)為子孫節(jié)點
target: customFormControls
}
}
})
KESION 科汛軟件
KESION 科汛軟件是國內(nèi)領(lǐng)先的在線教育軟件及私域社交電商軟件服務(wù)提供商,長期專注于為企業(yè)提供在線教育軟件及社交電商SaaS平臺解決方案。
公司核心產(chǎn)品云開店SaaS社交電商服務(wù)平臺、在線教育SaaS服務(wù)平臺、教育企業(yè)數(shù)字化SaaS云平臺、企微營銷助手、私有化獨立部署品牌網(wǎng)校和在線教育咨詢等。KESION 不斷通過技術(shù)創(chuàng)新,提供產(chǎn)品和服務(wù),助力企業(yè)向數(shù)字化轉(zhuǎn)型,通過科技驅(qū)動商業(yè)革新,讓商業(yè)變得更智慧!
微信之所以受到這么多人的喜愛和支持,不僅僅因為它齊全的語音聊天功能和視頻聊天功能。這些年來微信的公眾號也受到許多人的支持。并且現(xiàn)在微信公眾號也受到許多人的支持和熱...
說起微信小程序demo源碼,肯定很多人還不太了解。微信小程序就是一種不需要下載,可以直接在微信客戶端使用的軟件,一開始微信在不太成熟的情況下,并沒有小程序。但是近年來,...