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