Vue.js里有watch監(jiān)聽(tīng)機(jī)制,很適合“一處改變,多處影響”的場(chǎng)景,在開(kāi)發(fā)小程序的過(guò)程中,自然也會(huì)遇到這樣的場(chǎng)景,下面介紹如何在小程序中實(shí)現(xiàn)watch監(jiān)聽(tīng)。
1. 定義watch.js
在根目錄(miniprogram)下創(chuàng)建watch.js,代碼如下:
// watch.js
const observe = (obj, key, watchFun, deep, page) => {
let oldVal = obj[key]
// 如果監(jiān)聽(tīng)對(duì)象是object類(lèi)型并且指定deep(深度監(jiān)聽(tīng))
if (oldVal !== null && typeof oldVal === 'object' && deep) {
// 遞歸子集,依次執(zhí)行observe()
Object.keys(oldVal).forEach(item => {
observe(oldVal, item, watchFun, deep, page)
})
}
// 使用Object.defineProperty()劫持?jǐn)?shù)據(jù)的寫(xiě)操作,在監(jiān)聽(tīng)對(duì)象改變后執(zhí)行傳入的watchFun
Object.defineProperty(obj, key, {
configurable: true,
enumerable: true,
set(value) {
if (value === oldVal) return
watchFun.call(page, value, oldVal)
oldVal = value
},
get() {
return oldVal
}
})
}
export const setWatcher = (page) => {
// 頁(yè)面里的data字段
const data = page.data
// 頁(yè)面里的watch字段
const watch = page.watch
// 對(duì)watch里列舉的每一個(gè)字段(需要監(jiān)聽(tīng)的字段)執(zhí)行observe()
Object.keys(watch).forEach(key => {
let targetData = data
const targetKey = key
// 支持deep深度監(jiān)聽(tīng),使用deep時(shí)需要配合handler使用,否則直接編寫(xiě)函數(shù)
const watchFun = watch[key].handler || watch[key]
const deep = watch[key].deep
observe(targetData, targetKey, watchFun, deep, page)
})
}
2. 使用方法
在需要使用監(jiān)聽(tīng)機(jī)制頁(yè)面的js文件(如index.js)onLoad鉤子里,執(zhí)行setWatch(使用import關(guān)鍵詞從watch.js引入),并傳入當(dāng)前頁(yè)面實(shí)例this,完成初始化。
添加watch對(duì)象,內(nèi)部寫(xiě)入需要被監(jiān)聽(tīng)的字段以及執(zhí)行函數(shù):
// index.js
import { setWatch } from '../../watch.js'
Page({
data: { ... },
watch: {
// 需要監(jiān)聽(tīng)的字段
foo(val) {
console.log('foo變化了,變化后的值是', val)
... // 具體操作
}
},
// watch初始化,傳入當(dāng)前頁(yè)面實(shí)例this
onLoad() {
setWatch(this)
}
})