VUE设置和清除定时器

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

方法一、在生命周期函数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
},
阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: vue