1. Vue组件中使用定时器
在vue中使用定时器,很多情况下,进入和退出vue界面,都没有清除定时器,从而导致有很多定时器一起工作,这样肯定是不行的,接下来就使用当用户进入界面时启用定时器,当用户离开当前界面时就清除定时器。
<template>
<div></div>
</template>
<script>
export default {
name: "Home",
data() {
return {
timer: null,
};
},
methods: {
setTimer() {
if(this.timer == null) {
this.timer = setInterval( () => {
// 这里处理需要定时执行函数
console.log('开始定时...每过一秒执行一次')
}, 1000)
}
}
},
mounted() {
// 每次进入界面时,先清除之前的所有定时器,然后启动新的定时器
clearInterval(this.timer);
this.timer = null;
this.setTimer();
},
destroyed() {
// 每次离开当前界面时,清除定时器
clearInterval(this.timer);
this.timer = null;
},
};
</script>
<style>
</style>