I'm facing a problem where an Interval from a Vue component keeps running when I navigate to another route of my app.
I'm using Vue router, having the next configuration:
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/login',
name: 'Login',
component: LoginMenu
},
{
path: '/canvas',
name: 'Canvas',
component: AllElement
},
{
path: '/querybuilder',
name: 'QueryBuilder',
component: QueryBuilder
},
{
path: '/dashboard',
name: 'Dashboard',
component: Dashboard
}
]
The interval is in the AllElement component. As I'm using Vue router, AllElement is loaded into the router-view
, and when I switch to Home.vue component, it will be loaded into the router-view
but the AllElement's interval will keep running.
Here's where the interval is being initiated
mounted() {
this.fetchLastBucketData();
setInterval(() => {
this.fetchLastBucketData();
}, 3000);
}
Any solutions?
CodePudding user response:
Assign the setInterval
to a data property and clear when the component is unmounted :
data(){
return{
interval:null;
};
},
mounted() {
this.fetchLastBucketData();
this.interval = setInterval(() => {
this.fetchLastBucketData();
}, 3000);
},
unmounted(){ // destroyed in Vue 2
clearInterval(this.interval)
}
in Composition API :
import {ref,onMounted,onUnmounted} from 'vue'
....
const interval =ref(null)
onMounted()=> {
fetchLastBucketData();
interval.value = setInterval(() => {
fetchLastBucketData();
}, 3000);
})
onUnmounted(()=>{
clearInterval(interval.value)
}
)
CodePudding user response:
I am assuming you are using Vue-3.
You need to add the code to clear the interval. Since you want the interval to stop on route change, so it should be placed in unmounted hook (destroyed in Vue-2). Something like this:
mounted() {
this.fetchLastBucketData();
this.canvasInterval = setInterval(() => {
this.fetchLastBucketData();
}, 3000);
}
unmounted() {
clearInterval(this.canvasInterval); // - Clears Interval
}