什么时候使用Behavior
当多个组件执行的方法和需要的数据类似时,我们可以提取出公共部分写入混入对象中,哪个组件需要用直接引入即可。
使用Behavior例子
注册一个 behavior,接受一个 Object 类型的参数。
// my-behavior.js
module.exports = Behavior({
properties: {
myBehaviorProperty: {
type: String
}
},
data: {
myBehaviorData: 123
},
attached: function(){},
methods: {
myBehaviorMethod: function(){}
}
})
// page中
const myBehavior = require('../../component/my-behavior');
Page({
behaviors: [myBehavior],
data: {},
onLoad: function () {
// myBehaviorMethod是my-behavior中的方法
this myBehaviorMethod(){
}
}
})
然后在wxml中调用data中的数据myBehaviorData
<view>
{{myBehaviorData}}
</view>
在页面中显示