最近工作上遇到一個(gè)問題,有個(gè)全局變量 red_heart,因?yàn)樗诤芏嗟胤接玫剑?dāng)它發(fā)生改變了,用到的地方也要改變。但是原生小程序并沒有像Vue這種相關(guān)的做法。所以我就想自己實(shí)現(xiàn)一個(gè)全局變量改變,用到這個(gè)變量的地方也重新渲染。
開始吧
首先全局變量里肯定要先有這個(gè) red_heart
1
2
3
|
globalData: { red_heart:0, }, |
然后要在onLaunch方法里給全局變量加一個(gè)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方法里面有一個(gè)this.globalDep.RedHeartDep.notifuy(),這個(gè)是啥。這是我在全局創(chuàng)建的一個(gè)Dep,簡(jiǎn)稱依賴收集。
代碼
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是一個(gè)數(shù)組,用來收集依賴,addSub和removeWatch,notifuy是用來告訴這個(gè)東西要去更新了。
那現(xiàn)在還有一個(gè)問題,就是這個(gè)依賴在哪里添加呢,當(dāng)然是在用到的地方添加,就是組件創(chuàng)建的時(shí)候。
附上組件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上添加依賴,在組件銷毀的時(shí)候也不要忘記把依賴刪除,這個(gè)id是小程序的一個(gè)編譯id,直接拿來用了。
害就這樣了就做好啦!
總結(jié)
到此這篇關(guān)于微信小程序如何監(jiān)聽全局變量的文章就介紹到這了,更多相關(guān)小程序監(jiān)聽全局內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://juejin.cn/post/6942319891911278599