微信小程序如何監(jiān)聽全局變量
最近工作上遇到一個問題,有個全局變量 red_heart,因為它在很多地方用到,當它發(fā)生改變了,用到的地方也要改變。但是原生小程序并沒有像Vue這種相關的做法。所以我就想自己實現一個全局變量改變,用到這個變量的地方也重新渲染。
開始吧
首先全局變量里肯定要先有這個 red_heart
globalData: { red_heart:0, },
然后要在onLaunch方法里給全局變量加一個Proxy代理。
Proxy很好理解,懂得都懂。
this.globalData = new Proxy(this.globalData, { get(target, key){ return target[key]; }, set:(target, key, value)=>{ if(key === "red_heart"){ this.globalDep.RedHeartDep.notifuy() } return Reflect.set(target, key, value); } });
主要看set方法里面有一個this.globalDep.RedHeartDep.notifuy(),這個是啥。這是我在全局創(chuàng)建的一個Dep,簡稱依賴收集。
代碼
globalDep:{ RedHeartDep:{ subs:[], addSub(watch){ this.subs.push(watch) }, removeWatch(id){ this.subs = this.subs.filter((item)=>{ return item.id != id }) }, notifuy(){ setTimeout(()=>{ this.subs.forEach(w=>w.update()) },0) } } }
subs是一個數組,用來收集依賴,addSub和removeWatch,notifuy是用來告訴這個東西要去更新了。
那現在還有一個問題,就是這個依賴在哪里添加呢,當然是在用到的地方添加,就是組件創(chuàng)建的時候。
附上組件js全部代碼:
const app = getApp() Component({ properties: { }, data: { red_heart:0 }, lifetimes:{ attached(){ let watch = { id:this.__wxExparserNodeId__, update:()=>{ this.setData({ red_heart:app.globalData.red_heart }) } } app.globalDep.RedHeartDep.addSub(watch) app.globalData.red_heart = app.globalData.red_heart }, detached(){ app.globalDep.RedHeartDep.removeWatch(this.__wxExparserNodeId__) } }, methods: { handClick(){ app.globalData.red_heart++ console.log(app.globalData) } } })
在attached上添加依賴,在組件銷毀的時候也不要忘記把依賴刪除,這個id是小程序的一個編譯id,直接拿來用了。
害就這樣了就做好啦!
總結
到此這篇關于微信小程序如何監(jiān)聽全局變量的文章就介紹到這了,更多相關小程序監(jiān)聽全局內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
bootstrap自定義樣式之bootstrap實現側邊導航欄功能
bootstrap自帶的響應式導航欄是向下滑動的,有時滿足不了個性化的需求,需要做一個類似于android drawerLayout 側滑的菜單,這就是我要實現的bootstrap自定義側滑菜單。接下來通過本文給大家介紹bootstrap實現側邊導航欄功能,感興趣的朋友一起看看吧2018-09-09