眾所周知,微信小程序的數(shù)據(jù)監(jiān)聽器observers只能在自定義組件中使用,如果想要在頁面中實(shí)現(xiàn)類似的功能,就只有通過其他的方法。其一就是通過模擬vue的watch來監(jiān)聽數(shù)據(jù)變化。
那么Page中應(yīng)該怎樣監(jiān)聽呢?
1.創(chuàng)建watch.js
新建一個(gè) watch.js 文件存放監(jiān)聽器的邏輯函數(shù),代碼如下:
// watch.js
const observe = (obj, key, watchFun, deep, page) => {
let oldVal = obj[key]
// 如果監(jiān)聽對(duì)象是object類型并且指定deep(深度監(jiān)聽)
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ù)的寫操作,在監(jiān)聽對(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) => {
// 頁面里的data字段
const data = page.data
// 頁面里的watch字段
const watch = page.watch
// 對(duì)watch里列舉的每一個(gè)字段(需要監(jiān)聽的字段)執(zhí)行observe()
Object.keys(watch).forEach(key => {
let targetData = data
const targetKey = key
// 支持deep深度監(jiān)聽,使用deep時(shí)需要配合handler使用,否則直接編寫函數(shù)
const watchFun = watch[key].handler || watch[key]
const deep = watch[key].deep
observe(targetData, targetKey, watchFun, deep, page)
})
}
2.在頁面中使用
在需要使用監(jiān)聽機(jī)制頁面的 js文件(如 index.js)的 onLoad 鉤子里執(zhí)行 setWatcher (使用 import 從watch.js引入),并傳入當(dāng)前頁面實(shí)例 this,完成初始化。添加 watch 對(duì)象,內(nèi)部寫入需要被監(jiān)聽的字段及執(zhí)行函數(shù):
// index.js
import { setWatcher } from '../../utils/watch.js'
Page({
data: { ... },
watch: {
// foo 是需要監(jiān)聽的字段
foo(val) {
console.log('foo變化了,變化后的值是', val)
... // 具體操作
}
},
// watch初始化,傳入當(dāng)前頁面實(shí)例this
onLoad() {
setWatcher(this)
}
})
tips:如果有多個(gè)頁面都需要使用watch監(jiān)聽,可以直接在app.js中引入該文件,注冊(cè)成全局函數(shù),這樣就不用每個(gè)文件都去引入watch.js了,只需要在使用的頁面onLoad的時(shí)候調(diào)用一次該函數(shù),就能愉快的使用watch了。
使用實(shí)例:
1.創(chuàng)建wtach.js,這里我在utils下面創(chuàng)建的
2.在需要監(jiān)聽的Page頁面引入
3.在onLoad里面初始化
?
4.進(jìn)行監(jiān)聽
這里我監(jiān)聽的data中的investoCode字段,并進(jìn)行具體操作文章來源:http://www.zghlxwxcb.cn/news/detail-536986.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-536986.html
到了這里,關(guān)于微信小程序Page監(jiān)聽數(shù)據(jù)變化不能使用observers的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!