文檔:
- 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,
});
},
},
});