天天看點

Vue:使用定時器timer及其清理hook:beforeDestory

方式一:定義data中定義timer

export default {
  data() {
    return {
      // 定義定時器
      timer: null,
    };
  },

  methods: {
    startTimer() {
      this.timer = setInterval(() => {
        // 需要做的事情
      }, 1000);
    },

    stopTimer() {
      clearInterval(this.timer);
      this.timer = null;
    },
  },

  mounted() {
    this.startTimer();
  },

  beforeDestroy() {
    this.stopTimer();
  },
};      

方式二:監聽事件

hook:beforeDestroy

export default {
  methods: {
    startTimer() {
      // 啟動計時器
      let timer = setInterval(() => {
        //需要做的事情
        console.log(11111);
      }, 1000);

      // 銷毀計時器
      this.$once('hook:beforeDestroy', () => {
        clearInterval(timer);
        timer = null;
      });
    },
  },

  mounted() {
    this.startTimer();
  },
};
      

參考

vue項目中使用$.once(‘hook:beforeDestory‘,() => {})清理定時器問題

繼續閱讀