[Vue] vue中setInterval的问题

vue中使用setInterval

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

而后再组件销毁前进行清除vue

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

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

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

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

解决

使用全局变量blog

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);
      })
相关文章
相关标签/搜索