一、使用方法
安装
npm install --save miniprogram-computed
构建npm
在开发者工具中依次点击“工具”——“构建npm”。
computed 基本用法
const computedBehavior = require('miniprogram-computed').behavior
Component({
behaviors: [computedBehavior],
data: {
a: 1,
b: 1,
},
// 添加computed选项
computed: {
sum(data) {
// 注意: computed 函数中不能访问 this ,只有 data 对象可供访问
// 这个函数的返回值会被设置到 this.data.sum 字段中
return data.a + data.b
},
},
})
<view>SUM = {{sum}}</view>
watch 基本用法
const computedBehavior = require('miniprogram-computed').behavior
Component({
behaviors: [computedBehavior],
data: {
a: 1,
b: 1,
sum: 2,
},
// 添加watch选项
watch: {
// 监听a和b
'a, b': function (a, b) {
this.setData({
sum: a + b,
})
},
},
})
<view>SUM = {{sum}}</view>
二、常见问题说明
我应该使用 computed 还是 watch ?
从原理上说, watch
的性能比 computed
更好;但 computed
的用法更简洁干净。
此外, computed
字段状态只能依赖于 data
和其他 computed
字段,不能访问 this
。如果不可避免要访问 this
,则必须使用 watch
代替。
watch 和小程序基础库本身的 observers 有什么区别?
- 无论字段是否真的改变,
observers
都会被触发,而watch
只在字段值改变了的时候触发,并且触发时带有参数。
关于 ** 通配符
在 watch
字段上可以使用 **
通配符,是它能够监听这个字段下的子字段的变化(类似于小程序基础库本身的 observers )。
const computedBehavior = require('miniprogram-computed').behavior
Component({
behaviors: [computedBehavior],
data: {
obj: {
a: 1,
b: 2,
},
},
watch: {
'obj.**': function (obj) {
this.setData({
sum: obj.a + obj.b,
})
},
},
methods: {
onTap() {
this.setData({
'obj.a': 10,
})
},
},
})
除此以外:
- 对于没有使用
**
通配符的字段,在watch
检查值是否发生变化时,只会进行粗略的浅比较(使用===
); - 对于使用了
**
通配符的字段,则会进行深比较,来尝试精确检测对象是否真的发生了变化,这要求对象字段不能包含循环(类似于JSON.stringify
)。
网友评论