微信小程序 computed 实现
- 安装 computed: computed
npm install --save miniprogram-computed
- 作为 behavior 引入
const computedBehavior = require('miniprogram-computed')
Component({
behaviors: [computedBehavior],
data: {
a: 0,
},
computed: {
b() {
// 计算属性同样挂在 data 上,每当进行 setData 的时候会重新计算
// 比如此字段可以通过 this.data.b 获取到
return this.data.a + 100
},
},
methods: {
onTap() {
this.setData({
a: ++this.data.a,
})
}
}
})
<view>data: {{a}}</view>
<view>computed: {{b}}</view>
<button bindtap="onTap">click</button>
- 把 Page({}) 修改为 Component({})
- 把基础版本库改到2.61 以上,详情-> 本地设置 -> 基础版本库
- 然后就可以愉快的使用computed属性了,使用方法和组件Component 组件用法一致
- computed 属性只能计算一层,当引用另一个计算属性时,会首先计算这个在计算引用的计算属性,导致计算值紊乱