新聞中心
computed
小程序自定義組件擴(kuò)展 behavior,計(jì)算屬性 computed 和監(jiān)聽器 watch 的實(shí)現(xiàn)。在 data 或者 properties 改變時(shí),會(huì)重新計(jì)算 computed 字段并觸發(fā) watch 監(jiān)聽器。

此 behavior 依賴開發(fā)者工具的 npm 構(gòu)建。具體詳情可查閱官方 npm 文檔。
使用方法
需要小程序基礎(chǔ)庫版本 >= 2.6.1 的環(huán)境。
你可以直接體驗(yàn)一下這個(gè)代碼片段,它包含了基本用法示例:https://developers.weixin.qq.com/s/gXK31mmZ73dd
安裝
npm install --save miniprogram-computed
computed 基本用法
const computedBehavior = require('miniprogram-computed')
Component({
behaviors: [computedBehavior],
data: {
a: 1,
b: 1,
},
computed: {
sum(data) {
// 注意: computed 函數(shù)中不能訪問 this ,只有 data 對(duì)象可供訪問
// 這個(gè)函數(shù)的返回值會(huì)被設(shè)置到 this.data.sum 字段中
return data.a + data.b
},
},
methods: {
onTap() {
this.setData({
a: this.data.b,
b: this.data.a + this.data.b,
})
}
}
})
A = {{a}}
B = {}
SUM = {{sum}}
watch 基本用法
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,
})
}
}
})
A = {{a}}
B = {}
SUM = {{sum}}
^1.0.0 與 ^2.0.0 版本差異
這個(gè) behavior 的 ^1.0.0 版本和 ^2.0.0 版本有較大差異。 ^2.0.0 版本基于小程序基礎(chǔ)庫 2.6.1 開始支持的 observers 定義段實(shí)現(xiàn),具有較好的性能。以下是版本之間主要區(qū)別的比較。
| 項(xiàng)目 | ^1.0.0 | ^2.0.0 |
|---|---|---|
| 支持的基礎(chǔ)庫最低版本 | 2.2.3 | 2.6.1 |
支持 watch 定義段 | 否 | 是 |
| 性能 | 相對(duì)較差 | 相對(duì)較好 |
常見問題說明
我應(yīng)該使用 computed 還是 watch ?
從原理上說, watch 的性能比 computed 更好;但 computed 的用法更簡潔干凈。
此外, computed 字段狀態(tài)只能依賴于 data 和其他 computed 字段,不能訪問 this 。如果不可避免要訪問 this ,則必須使用 watch 代替。
watch 和小程序基礎(chǔ)庫本身的 observers 有什么區(qū)別?
- 無論字段是否真的改變, observers 都會(huì)被觸發(fā),而 watch 只在字段值改變了的時(shí)候觸發(fā),并且觸發(fā)時(shí)帶有參數(shù)。
關(guān)于 ** 通配符
在 watch 字段上可以使用 ** 通配符,是它能夠監(jiān)聽這個(gè)字段下的子字段的變化(類似于小程序基礎(chǔ)庫本身的 observers)。示例代碼片段
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
})
}
}
})
除此以外:
- 對(duì)于沒有使用 ** 通配符的字段,在 watch 檢查值是否發(fā)生變化時(shí),只會(huì)進(jìn)行粗略的淺比較(使用 === );
- 對(duì)于使用了 ** 通配符的字段,則會(huì)進(jìn)行深比較,來嘗試精確檢測對(duì)象是否真的發(fā)生了變化,這要求對(duì)象字段不能包含循環(huán)(類似于 JSON.stringify )。
網(wǎng)站題目:創(chuàng)新互聯(lián)小程序教程:微信小程序框架擴(kuò)展·computed
文章鏈接:http://fisionsoft.com.cn/article/dhgcpge.html


咨詢
建站咨詢
