1、使用前准备
1.1、安装
//1、初始化项目
npm init
//2、安装miniprogram-computed
npm install --save miniprogram-computed
1.2、构建npm
点击开发者工具中的菜单栏:工具 --> 构建 npm
1.3、勾选“使用 npm 模块”选项
点击开发者工具中的菜单栏:详情 --> 本地设置
2、在component中使用
2.1、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,
})
}
}
});
<view>A = {{a}}</view>
<view>B = {{b}}</view>
<view>SUM = {{sum}}</view>
<button bindtap="onTap">click</button>
2.2、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,
})
}
}
});
<view>A = {{a}}</view>
<view>B = {{b}}</view>
<view>SUM = {{sum}}</view>
<button bindtap="onTap">click</button>