May 21, 2021 WeChat Mini Program Development Document
The applet customizes the component to extend the behavior, calculate the implementation of the properties computed and the listener watch. When data or properties change, the computed field is recalculated and the watch listener is triggered.
This behavior relies on the npm build of the developer tool. Details can be found in the official npm documentation.
An environment that requires a small program base library version of .
You can experience this snippet directly, which contains an example of basic usage: https://developers.weixin.qq.com/s/gXK31mmZ73dd
npm install --save miniprogram-computed
const computedBehavior = require('miniprogram-computed')
Component({
behaviors: [computedBehavior],
data: {
a: 1,
b: 1,
},
computed: {
sum(data) {
// 注意: computed 函数中不能访问 this ,只有 data 对象可供访问
// 这个函数的返回值会被设置到 this.data.sum 字段中
return data.a + data.b
},
},
methods: {
onTap() {
this.setData({
a: this.data.b,
b: this.data.a + this.data.b,
})
}
}
})
<view>A = {{a}}</view>
<view>B = {{b}}</view>
<view>SUM = {{sum}}</view>
<button bindtap="onTap">click</button>
const computedBehavior = require('miniprogram-computed')
Component({
behaviors: [computedBehavior],
data: {
a: 1,
b: 1,
sum: 2,
},
watch: {
'a, b': function(a, b) {
this.setData({
sum: a + b
})
},
},
methods: {
onTap() {
this.setData({
a: this.data.b,
b: this.data.a + this.data.b,
})
}
}
})
<view>A = {{a}}</view>
<view>B = {{b}}</view>
<view>SUM = {{sum}}</view>
<button bindtap="onTap">click</button>
There is a big difference between the version of this behavior, version 1.0.0, and version of .2.0.0. T he version of .2.0.0 is based on the observers definition segment implementation that has been supported since the beginning of the small program base library 2.6.1 and has good performance. The following is a comparison of the main differences between versions.
Project | ^1.0.0 | ^2.0.0 |
---|---|---|
The lowest version of the underlying library is supported | 2.2.3 | 2.6.1 |
Watch definition
watch
are supported
|
Whether | Is |
Performance | Relatively poor | Relatively good |
In principle, watches perform better than computed, but computed is cleaner and cleaner to use.
In addition, the computed field state can only depend on data and other computed fields and cannot access this. If it is inevitable to access this, you must use watch instead.
On the watch field, you can use the wildcard, which is its ability to listen for changes in sub-fields under this field (similar to observers of the applet base library itself). Sample snippet
const computedBehavior = require('miniprogram-computed')
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
})
}
}
})
Besides: