I found an issue in vue-router which triggers me a lot. Always when I switch between my routes, a new instance of the component is created. Further the old instances are not
There are 2 ways to solve this problem:
destroy
hookIf you use any outside event listeners, like setInterval
, addEventListener
, etc you also need to deregister them when your component gets destroyed, example:
{
name: '...',
template: '...',
data() {
return {
interval: undefined,
timeout: undefined
};
},
mounted() {
interval = setInterval(() => {console.log('Instance ' + this._uid + ' of myself is running')}, 500);
timeout = setTimeout(() => {console.log('Instance ' + this._uid + ' of myself is running')}, 500);
document.addEventListener('click', this.onOutsideClick);
},
beforeDestroy() {
// Cleanup interval
clearInterval(interval);
// Cleanup any pending timeouts
clearTimeout(timeout);
// Cleanup any event listeners outside the root of the element
document.removeEventListener('click', this.onOutsideClick);
},
methods: {
onOutsideClick() {
...
}
}
}
When using keepalive, Vue caches your component, and keeps it alive in the background, this means that only one instance will ever exists. This can potentially consume more memory if you have a large amount of routes