微信小程序文章推荐:微信小程序必备开发技能总结(不断更新)
一、微信小程序中的behaviors 什么?
微信小程序中的behaviors指的是一组件间,可以共享的代码,类似于Vue 中的mixins,它可以实现代码的复用。每个 behavior
可以包含一组属性、数据、生命周期函数和方法。组件引用它时,它的属性、数据和方法会被合并到组件中,生命周期函数也会在对应时机被调用。
二、创建behavior
js
module.exports = Behavior({
properties: {
name: {
type: String,
value: '未知'
}
},
data: {
time: new Date().getTime()
},
methods: {
updateTime() {
this.setData({
time: new Date().getTime()
})
}
},
lifetimes: {
created () {
console.log('behavior---created')
},
ready () {
console.log('behavior----ready')
}
}
})
在这个文件中:
- 使用微信小程序内置的
Behavior
方法创建了一个behavior - 在Behavior的参数对象中定义了
properties
,data
,methods
,lifetimes
- 使用module.exports进行了导出
三、 behavior 在组件中的使用
在项目根目录下创建components文件夹,再创建test 文件夹,选中test文件夹,鼠标右键新建Component,填写组件名称test。test.js中使用创建出来的behavior,具体使用方式如下:
test.js
js
const testBehavior = require('../../behaviors/test-behavior')
Component({
behaviors: [testBehavior],
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
}
})
在这个文件中:
- 使用
require
导入了前面我们创建的behavior - 在Component方法中的参数属性中,通过
behaviors
属性进行behavior的使用
test.wxml
html
<view>
<view>
<text>您的名字: {{name}}</text>
</view>
<view>
<text>时间戳:{{time}}</text>
</view>
<button type="primary" bindtap="updateTime">更新时间戳</button>
</view>
在pages/index/index.json中注册test组件
js
{
"usingComponents": {
"my-test": "/components/test/test"
}
}
pages/index/index.wxml中使用组件:
index.wxml
<view>
<my-test></my-test>
</view>
运行效果:

可以看到我们在test-behavior中定义创建的behavior,已经被调用了,点击更新时间戳的时候,时间戳也会更新。在控制台也能看到生命周期中的输出

四、behavior 中的定义和组件中定义了同名的优先级
- 首先来看看 properties 和, data, 我们在test组件中的test.js中的 properties和data属性定义相同的名称,但是值不同,来看下会优先使用哪个
test.js 修改如下
js
const testBehavior = require('../../behaviors/test-behavior')
Component({
behaviors: [testBehavior],
/**
* 组件的属性列表
*/
properties: {
name: {
type: String,
value: '组件中的未知'
}
},
/**
* 组件的初始数据
*/
data: {
time: new Date().getTime() + '组件中的时间戳'
},
/**
* 组件的方法列表
*/
methods: {
}
})
查看页面运行效果:

可以看到,当组件和behavior定义了相同字段的properties 和data字段时,会优先使用组件里面的。
再来看看methods,test.js中methods修改如下:
js
methods: {
updateTime() {
this.setData({
time: new Date().getTime() + '组件中更新了时间戳'
})
}
}
点击按钮查看运行效果:

可以看到依然是组件里面的方法优先级高于behavior定义的方法。
再来看看生命周期是怎么样的覆盖规则,在test.js中添加和behavior中定义相同的生命周期函数,打印不同的文案。
test.js 添加如下代码:
js
lifetimes: {
created () {
console.log('behavior---created---在组件中')
},
ready () {
console.log('behavior----ready0-----在组件中')
}
}
查看控制台运行效果: 可以看到behavior中的生命周期和组件中的生命周期都会打印,同一个生命周期函数,会先先打印behavior中的,在打印组件中的,同一个生命周期behavior中的先执行,后执行组件中的。
五、总结
本篇主要介绍了,behavior的创建方式,在组件中的使用方式,以及定义了相同的字段的覆盖规律,看了本篇,相信你已经对behavior 有了印象,好好利用behavior 可以提高到代码的复用率。
今天的分享就到这里了,感谢你的收看,小程序文章可关注uni-app,小程序知识储备