[Vue] vue中setInterval的问题

元气小坏坏 提交于 2021-01-24 02:20:17

vue中使用setInterval

      this.chatTimer = setInterval(() => {
        console.log(this.chatTimer);
        this.chatMsg();
      }, 1000);

然后再组件销毁前进行清除

beforeDestroy() {
    clearInterval(this.chatTimer);
    this.chatTimer = null;
}

根据 setInterval 返回的 id 打印来看,请除定时器并没有成功

但是这样不行,定时器在局部更新的时候会多次赋值.更改了一种写法,加了一重判断之后依旧无法解决.

      if (!this.chatTimer) {
        this.chatTimer = setInterval(() => {
          console.log(this.chatTimer);
          this.chatMsg();
        }, 1000);
      }

解决

使用全局变量

     window.chatTimer = setInterval(() => {
        console.log(window.chatTimer);
        this.chatMsg();
      }, 1000);
destroyed() {
      clearInterval(window.liaotianTimer);
    },

最终解决

      const chatTimer = setInterval(() => {
        console.log(chatTimer);
        this.chatMsg();
      }, 1000);

      this.$once('hook:beforeDestroy', () => {
        clearInterval(chatTimer);
      })
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!