美文网首页
Vue中在组件销毁时清除定时器

Vue中在组件销毁时清除定时器

作者: 好多柱 | 来源:发表于2021-07-15 11:48 被阅读0次

在mounted中创建并执行定时器,然后在beforeDestroy或者destroyed中清除定时器

<template>
      <div class="about">
      </div>
    </template>
    <script>
    export default {
        name: "about",
        data() {
            return {
                //接收定时器
                timer: ""
            };
        },
        mounted() {
            let _this = this;
            let num = 0;
            //创建并执行定时器
            this.timer = setInterval(() => {
              //当num等于100时清除定时器
                if (num == 100) {
                    clearInterval(_this.timer);
                }
                console.log(num++);
            }, 1000);
        },
        beforeDestroy() {
            //清除定时器
            clearInterval(this.timer);
            console.log("beforeDestroy");
        },
        destroyed() {
            //清除定时器
            //clearInterval(this.timer);
            console.log("destroyed");
        }
    };
    </script>
    <style scoped>
    </style>

如果用到了\color{#e897d2}{keep-alive}缓存组件,组件是不会被销毁的,可以使用beforeRouteLeave ,离开路由之前执行的函数

  beforeRouteLeave (to, from, next) {
    // ...
    if(this.timer){
      clearInterval(this.timer)
    }
    next()
  },

相关文章

网友评论

      本文标题:Vue中在组件销毁时清除定时器

      本文链接:https://www.haomeiwen.com/subject/bbmppltx.html