音乐网站建设论文,汽车租赁网站的设计与实现,服装厂招代理,写个网页多少钱1. 什么是 behaviors 2. behaviors 的工作方式 3. 创建 behavior
调用 Behavior(Object object) 方法即可创建一个共享的 behavior 实例对象#xff0c;供所有的组件使用#xff1a;
4. 导入并使用 behavior 5. behavior 中所有可用的节点 6. 同名字段的覆盖和组合规则* 关…1. 什么是 behaviors 2. behaviors 的工作方式 3. 创建 behavior
调用 Behavior(Object object) 方法即可创建一个共享的 behavior 实例对象供所有的组件使用
4. 导入并使用 behavior 5. behavior 中所有可用的节点 6. 同名字段的覆盖和组合规则* 关于详细的覆盖和组合规则大家可以参考微信小程序官方文档给出的说明 https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/behaviors.html
附官方文档-behaviors
behaviors 是用于组件间代码共享的特性类似于一些编程语言中的 “mixins” 或 “traits”。
每个 behavior 可以包含一组属性、数据、生命周期函数和方法。组件引用它时它的属性、数据和方法会被合并到组件中生命周期函数也会在对应时机被调用。 每个组件可以引用多个 behavior behavior 也可以引用其它 behavior 。
详细的参数含义和使用请参考 Behavior 参考文档。
组件中使用
组件引用时在 behaviors 定义段中将它们逐个列出即可。
代码示例
在开发者工具中预览效果
// my-component.js
var myBehavior require(my-behavior)
Component({behaviors: [myBehavior],properties: {myProperty: {type: String}},data: {myData: my-component-data},created: function () {console.log([my-component] created)},attached: function () { console.log([my-component] attached)},ready: function () {console.log([my-component] ready)},methods: {myMethod: function () {console.log([my-component] log by myMethod)},}
})在上例中 my-component 组件定义中加入了 my-behavior
而 my-behavior 结构为
// my-behavior.js
module.exports Behavior({behaviors: [],properties: {myBehaviorProperty: {type: String}},data: {myBehaviorData: {}},attached: function(){},methods: {myBehaviorMethod: function(){}}
})属性myBehaviorProperty数据字段myBehaviorData方法myBehaviorMethod生命周期函数attached、created、ready
这将使 my-component 最终结构为
属性myBehaviorProperty、myProperty数据字段myBehaviorData、myData方法myBehaviorMethod、myMethod生命周期函数attached、created、ready
当组件触发生命周期时上例生命周期函数执行顺序为
[my-behavior] created[my-component] created[my-behavior] attached[my-component] attached[my-behavior] ready[my-component] ready
详细规则参考 同名字段的覆盖和组合规则。
同名字段的覆盖和组合规则
组件和它引用的 behavior 中可以包含同名的字段对这些字段的处理方法如下
如果有同名的属性 (properties) 或方法 (methods) 若组件本身有这个属性或方法则组件的属性或方法会覆盖 behavior 中的同名属性或方法若组件本身无这个属性或方法则在组件的 behaviors 字段中定义靠后的 behavior 的属性或方法会覆盖靠前的同名属性或方法在 2 的基础上若存在嵌套引用 behavior 的情况则规则为引用者 behavior 覆盖 被引用的 behavior 中的同名属性或方法。 如果有同名的数据字段 (data) 若同名的数据字段都是对象类型会进行对象合并其余情况会进行数据覆盖覆盖规则为 引用者 behavior 被引用的 behavior 、 靠后的 behavior 靠前的 behavior。优先级高的覆盖优先级低的最大的为优先级最高 生命周期函数和 observers 不会相互覆盖而是在对应触发时机被逐个调用 对于不同的生命周期函数之间遵循组件生命周期函数的执行顺序对于同种生命周期函数和同字段 observers 遵循如下规则 behavior 优先于组件执行被引用的 behavior 优先于 引用者 behavior 执行靠前的 behavior 优先于 靠后的 behavior 执行 如果同一个 behavior 被一个组件多次引用它定义的生命周期函数和 observers 不会重复执行。