W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
behaviors 是用于組件間代碼共享的特性,類似于一些編程語言中的 mixins
每個(gè) behavior 可以包含一組屬性、數(shù)據(jù)、生命周期函數(shù)和方法,組件引用它時(shí),它的屬性、數(shù)據(jù)和方法會(huì)被合并到組件中,生命周期函數(shù)也會(huì)在對(duì)應(yīng)時(shí)機(jī)被調(diào)用。每個(gè)組件可以引用多個(gè) behavior 。 behavior 也可以引用其他 behavior 。
behavior 需要使用 Behavior() 構(gòu)造器定義。
代碼示例
module.exports = Behavior({
behaviors: [],
properties: {
myBehaviorProperty: {
type: String
}
},
data: {
myBehaviorData: {}
},
attached: function(){},
methods: {
myBehaviorMethod: function(){}
}
})
組件引用時(shí),在 behaviors 定義段中將它們逐個(gè)列出即可。
代碼示例
var myBehavior = require('my-behavior')
Component({
behaviors: [myBehavior],
properties: {
myProperty: {
type: String
}
},
data: {
myData: {}
},
attached: function(){},
methods: {
myMethod: function(){}
}
})
在上例中, my-component 組件定義中加入了 my-behavior ,而 my-behavior 中包含有 myBehaviorProperty 屬性、 myBehaviorData 數(shù)據(jù)字段、 myBehaviorMethod 方法和一個(gè) attached 生命周期函數(shù)。這將使得 my-component 中最終包含 myBehaviorProperty 、 myProperty 兩個(gè)屬性, myBehaviorData 、 myData 兩個(gè)數(shù)據(jù)字段,和 myBehaviorMethod 、 myMethod 兩個(gè)方法。當(dāng)組件觸發(fā) attached 生命周期時(shí),會(huì)依次觸發(fā) my-behavior 中的 attached 生命周期函數(shù)和 my-component中的 attached 生命周期函數(shù)。
組件和它引用的 behavior 中可以包含同名的字段,對(duì)這些字段的處理方法如下:
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: