Unc*_*oke 5 javascript setinterval vue.js vuejs2
在我用 VUE 制作的 SPA 中,我有一个组件运行一些递归的 setInterval 函数(这是一个倒计时)。当我将视图切换到另一个组件时,我注意到倒计时在后台继续,但我更喜欢销毁 setInterval。
我尝试使用具有倒计时的全局数据,然后在销毁的钩子上销毁它,但它不起作用。
这是我的代码:
data: function () {
return {
counters: ""
}
}),
methods: {
countdown(index, exp) {
...
this.counters = setInterva()
...
},
},
destroyed(){
console.log(this.counters); // returns a progressive integer
clearInterval(this.counters);
console.log(this.counters); // returns same integer
this.counters = 0;
console.log("destroyed");
}
Run Code Online (Sandbox Code Playgroud)
但是在控制台中我得到了:
摧毁
app.js:64433 0
app.js:64398 缺少 counter_1 。<--- 这意味着计数器仍在运行
感谢您的任何建议!
这里可能会发生两种情况,具体取决于您countdown是否打电话:
1.countdown没有被调用
countdown(index, exp)需要在钩子中定义,created如下所示。此外,为了实现预期的功能,应该将方法foo()绑定到此间隔。
created: function(){
this.counterInterval = setInterval(
function()
{
this.foo();
}.bind(this), 500);
return this.foo();
},
destoyed: function(){
clearInterval( this.counterInterval )
},
Run Code Online (Sandbox Code Playgroud)
2.countdown被正确调用,但组件实际上没有被销毁
如果错误实际上是对“销毁”组件含义的误解,因此组件没有被销毁,则可以使用与上面相同的代码,但JSX 内的data有界属性isShowing: true将解决问题。
只需执行 v-if 检查isShowing,然后在元素处于视图中时执行事件侦听器。如果该元素在视图中,那么我们就有isShowing===true。否则,错误。
小智 5
在 vue3 中,destroy() 和 beforeDestroy() 已被弃用。
使用 unmount() 或 beforeUnmount() 代替。
beforeUnmount(){
clearInterval(this.counters);
}
Run Code Online (Sandbox Code Playgroud)