文档:
- npm: https://www.npmjs.com/package/miniprogram-computed
- github: https://github.com/wechat-miniprogram/computed
安装
npm install --save miniprogram-computed
注意:以下示例基于版本miniprogram-computed: ^4.0.4
computed 基本用法
const computedBehavior = require("miniprogram-computed").behavior;
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,
});
},
},
});
watch 基本用法
const computedBehavior = require("miniprogram-computed").behavior;
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,
});
},
},
});