W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
定義:behaviors 用于組件間代碼共享,類(lèi)似于一些編程語(yǔ)言中的“mixins”或“traits”。
代碼示例
在開(kāi)發(fā)者工具中打開(kāi)// my-behavior.js
module.exports = Behavior({
behaviors: [],
properties: {
myBehaviorProperty: {
type: String,
value: 'behavior'
}
},
data: {
myBehaviorData: {}
},
attached: function(){},
methods: {
myBehaviorMethod: function(){}
}
});
組件引用時(shí),需在 behaviors 定義段中將它們逐個(gè)列出。
代碼示例
// my-component.js
var myBehavior = require('my-behavior')
Component({
behaviors: [myBehavior],
properties: {
myProperty: {
type: String,
value: 'component'
}
},
data: {
myData: {}
},
attached: function(){},
methods: {
myMethod: function(){}
}
});
通過(guò)上面的例子可知:
組件和它引用的 behavior 中可以包含同名的字段,對(duì)這些字段的處理方法如下:
自定義組件可以通過(guò)引用內(nèi)置的 behavior 來(lái)獲得內(nèi)置組件的一些行為。
代碼示例
在開(kāi)發(fā)者工具中打開(kāi)Component({
behaviors: ['swan://form-field']
});
解釋?zhuān)菏棺远x組件有類(lèi)似于表單控件的行為。form 組件可以識(shí)別這些自定義組件,并在 submit 事件中返回組件的字段名及其對(duì)應(yīng)字段值。這將為它添加以下兩個(gè)屬性:
屬性名 | 類(lèi)型 | 描述 | 最低版本 |
---|---|---|---|
name | String | 在表單中的字段名 | 1.13.29 |
value | 任意 | 在表單中的字段值 | 1.13.29 |
從基礎(chǔ)庫(kù)版本 2.0.5 開(kāi)始提供支持。
解釋?zhuān)菏棺远x組件支持 export 定義段。這個(gè)定義段可以用于指定組件被 selectComponent 調(diào)用時(shí)的返回值。
未使用這個(gè)定義段時(shí), selectComponent 將默認(rèn)返回自定義組件的 this 。使用這個(gè)定義段時(shí),將以這個(gè)定義段的函數(shù)返回值代替。
代碼示例
在開(kāi)發(fā)者工具中打開(kāi)// 自定義組件的js文件
Component({
behaviors: ['swan://component-export'],
export() {
return { componentField: 'componentValue' }
}
});
<!-- 使用自定義組件時(shí),對(duì)于自定義組件的引用模板 -->
<my-component id="custom-id" />
this.selectComponent('#custom-id') // 等于 { componentField: 'componentValue' }
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)系方式:
更多建議: