方法一、在生命周期函数beforeDestroy中清除 

data() {
    return {
      timer: null;
    };
},
created() {    
    // 设置定时器,5s执行一次
    this.timer = setInterval(() => {
      console.log('setInterval');
    }, 5000);
}
beforeDestroy () {
    //清除定时器
    clearInterval(this.timer);
    this.timer = null;
}

方法二、使用hook:beforedestroy(推荐)

created() {
    // 设置定时器,5s执行一次
    let timer = setInterval(() => {
      console.log('setInterval');
    }, 5000);
    // 离开当前页面时销毁定时器
    this.$once('hook:beforeDestroy', () => {
      clearInterval(timer);
      timer = null;
    })
}

该方法与在生命周期钩子beforeDestroy中清除定时器的操作原理一样,但更有优势

1.无需在vue实例上定义定时器,减少不必要的内存浪费

2.设置和清除定时器的代码放在一块,可读性维护性更好

三、beforeDestroy函数没有触发的情况

1、原因

<router-view>外层包裹了一层<keep-alive>

< keep-alive > 有缓存的作用,可以使被包裹的组件状态维持不变,当路由被 keep-alive 缓存时不走 beforeDestroy 生命周期。被包含在 < keep-alive > 中创建的组件,会多出两个生命周期钩子: activated 与 deactivated。

activated
在组件被激活时调用,在组件第一次渲染时也会被调用,之后每次keep-alive激活时被调用。

deactivated
在组件失活时调用。

2、解决方案

借助 activated 和 deactivated 钩子来设置和清除定时器

(1)生命周期钩子

created() {
    // 页面激活时设置定时器
    this.$on("hook:activated", () => {
        let timer = setInterval(()=>{
          console.log("setInterval");
        },1000)
    })
    // 页面失活时清除定时器
    this.$on("hook:deactivated", ()=>{
      clearInterval(timer);
      timer = null;
    })
  }

(2)hook

data() {
    return {
      timer: null // 定时器
    }
},
activated() {
    // 页面激活时开启定时器
    this.timer = setInterval(() => {
      console.log('setInterval');
    }, 5000)
},
deactivated() {
    // 页面关闭(路由跳转)时清除定时器
    clearInterval(this.timer)
    this.timer = null
},
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。