定时器的销毁

2020-01-15  本文已影响0人  小蜗牛的碎碎步
时钟组件
<template>
    <div>{{getTimeLock}}</div>
</template>

<script>
    export default {
        name: "TimeLock",
        data() {
            return {
                time: new Date(),
                inter: null
            }
        },
        computed: {
            getTimeLock() {
                let year = this.time.getFullYear();
                let month = this.time.getMonth() + 1;
                let day = this.time.getDate();
                let hour = this.time.getHours();
                let minute = this.time.getMinutes();
                let second = this.time.getSeconds();

                return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
            }
        },
        mounted() {
            var _this = this;
            setInterval(function () {
                console.log(_this.getTimeLock);
               _this.time = new Date(_this.time.getTime() + 1000);
            }, 1000);
        },
        methods: {},
        beforeDestroy() {

        },
        destroyed() {
            console.log("时钟组件被销毁!");
        }
    }
</script>
父组件
  <button @click="isShowTime = !isShowTime">是否显示时钟</button>
  <time-lock v-if="isShowTime"></time-lock>
执行结果
屏幕快照 2020-01-15 11.53.26.png

从上图可得知:虽然组件已经被销毁,但是定时器还在运行。

定时器销毁时机

beforeDestroy或者destroyed中

 beforeDestroy() {
       //clearInterval(this.inter);
        },
 destroyed() {
        console.log("时钟组件被销毁!");
        clearInterval(this.inter);
        }
内存泄漏

未及时清理的定时器会导致内存泄漏

上一篇 下一篇

猜你喜欢

热点阅读