实现轮询事件

一、需求

移动端实现用户权限判断,使用 uniapp 

二、实现方法

1、拿到用户数据之后,通过参数进行用户身份判断,显示对应的权限

在 app.vue 中调用接口查询用户信息并保存到缓存;在 home.vue 中查询身份信息并判断显示

问题:调用接口拿到数据返回保存在页面加载获取身份信息之后才完成

2、解决办法,使用轮询的方式进行查询是否有对应的信息数据保存到缓存中

三、完整代码

onLoad() {
    this.startRoundRobin();
  },
  methods: {
    startRoundRobin() {
      // 设置间隔和持续时间
      const interval = 1000; // 每隔1000毫秒(1秒)执行一次
      const duration = 10000; // 总共执行10秒钟
      let count = 0; // 计数器
      this.intervalId = setInterval(() => {
        // console.log(count);
        count++;
        if (count * interval >= duration) {
          this.stopRoundRobin();
          this.currentIndex = 100;
        } else {
          const info = uni.getStorageSync("userInfo");
          if (!info) {
            this.loading = true;
          } else {
            this.loading = false;
            this.stopRoundRobin();
          }
        }
      }, interval);
    },
    stopRoundRobin() {
      if (this.intervalId) {
        clearInterval(this.intervalId);
      }
    },
  },

 

posted @ 2024-12-13 10:27  殳苓  阅读(61)  评论(0)    收藏  举报