最近工作上遇到一個問題,有個全局變量 red_heart,因為它在很多地方用到,當它發生改變了,用到的地方也要改變。但是原生小程序并沒有像Vue這種相關的做法。所以我就想自己實現一個全局變量改變,用到這個變量的地方也重新渲染。
開始吧
首先全局變量里肯定要先有這個 red_heart
1
2
3
|
globalData: { red_heart:0, }, |
然后要在onLaunch方法里給全局變量加一個Proxy代理。
Proxy很好理解,懂得都懂。
1
2
3
4
5
6
7
8
9
10
11
|
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(),這個是啥。這是我在全局創建的一個Dep,簡稱依賴收集。
代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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是用來告訴這個東西要去更新了。
那現在還有一個問題,就是這個依賴在哪里添加呢,當然是在用到的地方添加,就是組件創建的時候。
附上組件js全部代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
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,直接拿來用了。
害就這樣了就做好啦!
總結
到此這篇關于微信小程序如何監聽全局變量的文章就介紹到這了,更多相關小程序監聽全局內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://juejin.cn/post/6942319891911278599