W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎勵
behaviors
是用于組件間代碼共享的特性,類似于一些編程語言中的“mixins”或“traits”。
每個 behavior
可以包含一組屬性、數(shù)據(jù)、生命周期函數(shù)和方法,組件引用它時(shí),它的屬性、數(shù)據(jù)和方法會被合并到組件中,生命周期函數(shù)也會在對應(yīng)時(shí)機(jī)被調(diào)用。每個組件可以引用多個 behavior
。behavior
也可以引用其他 behavior
。
behavior
需要使用 Behavior()
構(gòu)造器定義。
// my-behavior.js
module.exports = Behavior({
behaviors: [],
properties: {
myBehaviorProperty: {
type: String
}
},
data: {
myBehaviorData: {}
},
attached() {},
methods: {
myBehaviorMethod() {}
}
})
組件引用時(shí),在 behaviors 定義段中將它們逐個列出即可。
組件引用時(shí),在 behaviors 定義段中將它們逐個列出即可。 代碼示例:
// my-component.js
const myBehavior = require('my-behavior')
Component({
behaviors: [myBehavior],
properties: {
myProperty: {
type: String
}
},
data: {
myData: {}
},
attached() {},
methods: {
myMethod() {}
}
})
// my-component.js
const myBehavior = require('my-behavior')
Component({
behaviors: [myBehavior],
properties: {
myProperty: {
type: String
}
},
data: {
myData: {}
},
attached() {},
methods: {
myMethod() {}
}
})
在上例中, my-component 組件定義中加入了 my-behavior ,而 my-behavior 中包含有 myBehaviorProperty 屬性、 myBehaviorData 數(shù)據(jù)字段、 myBehaviorMethod 方法和一個 attached 生命周期函數(shù)。這將使得 my-component 中最終包含 myBehaviorProperty 、 myProperty 兩個屬性, myBehaviorData 、 myData 兩個數(shù)據(jù)字段,和 myBehaviorMethod 、 myMethod 兩個方法。當(dāng)組件觸發(fā) attached 生命周期時(shí),會依次觸發(fā) my-behavior 中的 attached 生命周期函數(shù)和 my-component 中的 attached 生命周期函數(shù)。
組件和它引用的 behavior 中可以包含同名的字段,對這些字段的處理方法如下:
自定義組件可以通過引用內(nèi)置的 behavior 來獲得內(nèi)置組件的一些行為。
Component({
behaviors: ['qq://form-field']
})
在上例中, qq://form-field 代表一個內(nèi)置 behavior ,它使得這個自定義組件有類似于表單控件的行為。 內(nèi)置 behavior 往往會為組件添加一些屬性。在沒有特殊說明時(shí),組件可以覆蓋這些屬性來改變它的 type 或添加 observer 。
使自定義組件有類似于表單控件的行為。 form 組件可以識別這些自定義組件,并在 submit 事件中返回組件的字段名及其對應(yīng)字段值。這將為它添加以下兩個屬性。
屬性名 | 類型 | 描述 |
---|---|---|
name | String | 在表單中的字段名 |
value | 任意 | 在表單中的字段值 |
使自定義組件支持 export 定義段。這個定義段可以用于指定組件被 selectComponent 調(diào)用時(shí)的返回值。 未使用這個定義段時(shí), selectComponent 將返回自定義組件的 this (插件的自定義組件將返回 null )。使用這個定義段時(shí),將以這個定義段的函數(shù)返回值代替。
代碼示例:
// 自定義組件 my-component 內(nèi)部
Component({
behaviors: ['qq://component-export'],
export() {
return {myField: 'myValue'}
}
})
<!-- 使用自定義組件時(shí) -->
<my-component id="the-id" />
this.selectComponent('#the-id') // 等于 { myField: 'myValue' }
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: