您当前的位置: 首页 > 

彭世瑜

暂无认证

  • 2浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

彭世瑜 发布时间:2021-10-26 09:41:48 ,浏览量:2

方式一:定义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‘,() => {})清理定时器问题

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.7957s