Behavior
概念:用与小程序中组件间代码共享的特性,类似于一些编程语言的 "mixins", "traits"
作用:
- 每一个behavior 可以包含一些属性,数据,生命周期函数,方法
- 在组件中引用它时,它的属性,数据和方法会被合并到组件中,生命周期函数也会在对应的时机被调用
- 每个组件可以引用多个behavior,behavior也可以引用其它的behavior
定义一个behavior: (就是一个js文件,按照需求,要求,合理编辑)
首先看下behavior 的常规结构
// my-behavior.js
// 在behavior 中使用 behavior 导入
var mySecondBehavior = require('my-second-behavior')
var mySecondBehavior = require('my-second-behavior')
//导出
module.exports = Behavior({
//注册导入的behavior
behaviors: [myThirdBehavior, mySecondBehavior],
properties:{
myBehaviorProperty: {
type: String
}
},
data:{},
//生命周期
created: function () {},
attached: function () {},
ready: function () {},
//方法
methods: { }
})
在组件中使用behavior
// my-component.js
//导入要使用的behavior (文件名 大写的使用-替换)
var myBehavior = require('my-behavior')
var mySecondBehavior = require('my-second-behavior')
Component({
// 在注册behavior 注册的behavior中的方法名如果相同,那么后面的会覆盖
behaviors: [myBehavior, mySecondBehavior],
properties: {
myProperty: {
type: String
}
},
// 同理 data 也会覆盖 合并
data:{}
})
以上就是behavior 的基本使用 然后在page中正常引用组件就可以
页面中向behavior 传旨方法同页面向组件传值
<!-- 引用组件的页面模版 -->
<view>
<my-component my-behavior-property="behavior-property【my-behavitor.js】" my-property="my-property">
</my-component>
</view>
更多可以结合开发者文档中的实例了解 微信开发者工具behavior
behavior 的生命周期
当组件触发生命周期时,生命周期函数执行顺序为:
[my-behavior] created
[my-component] created
[my-behavior] attached
[my-component] attached
[my-behavior] ready
[my-component] ready
生命周期函数不会相互覆盖,而是在对应触发时机被逐个调用:
- 对于不同的生命周期函数之间,遵循组件生命周期函数的执行顺序;
- 对于同种生命周期函数,遵循如下规则:
behavior
优先于组件执行;子 behavior
优先于父 behavior
执行;靠前的 behavior
优先于靠后的 behavior
执行;- 如果同一个
behavior
被一个组件多次引用,它定义的生命周期函数只会被执行一次。