微信小程序如何监听全局变量

时间:2022-06-01 14:06:37

最近工作上遇到一个问题,有个全局变量 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