创建的定时器代码和销毁定时器的代码没有放在一起,通常很容易忘记去清理这个定时器,不容易维护;
因此,使用this.$once(‘hook:beforeDestory’,()=>{});
直接在需要定时器的方法或者生命周期函数中声明并销毁
实现代码:
export default{
methods:{
fun1(){
const timer = setInterval(()=>{
//具体执行代码
console.log('1');
},1000);
this.$once('hook:beforeDestory',()=>{
clearInterval(timer);
timer = null;
})
}
}
}