Reputation: 1185
I'm working on a spa project using vue.js. In one component i'm sending ajax request after a while. I"m using vue-router to navigate. when i leaving the route and entering to another component, the ajax request still executing. How do i prevent/destroy the event executing? Here is my code example:
export default {
data() {
return {
};
},
methods: {
onLoad() {
setInterval(function(){
//sending ajax request
}, 5000);
},
},
mounted() {
this.onLoad();
},
}
Upvotes: 5
Views: 1919
Reputation: 7851
You need to save the interval ID in your Vue instance so that you can remove it later by calling clearInterval
. Here is how you can achieve that:
export default {
methods: {
onLoad() {
this.intervalId = setInterval(() => {
//sending ajax request
}, 5000)
}
},
mounted() {
this.onLoad()
},
beforeDestroy() {
clearInterval(this.intervalId)
}
}
EDIT: intervalId
doesn't need to be reactive.
Upvotes: 9