时钟组件
<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>
执行结果

从上图可得知:虽然组件已经被销毁,但是定时器还在运行。
定时器销毁时机
beforeDestroy或者destroyed中
beforeDestroy() {
//clearInterval(this.inter);
},
destroyed() {
console.log("时钟组件被销毁!");
clearInterval(this.inter);
}
内存泄漏
未及时清理的定时器会导致内存泄漏
网友评论