vue-router creates always a new Component instance

余生长醉 提交于 2019-12-01 08:01:11
Ferrybig

There are 2 ways to solve this problem:

Properly cleaning up in the destroy hook

If 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() {
            ...
        }
    }
}

Using keep-alive to keep the component alive

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

<keep-alive>
    <router-view></router-view>
</keep-alive>

Always when I switch between my routes, a new instance of the component is created.

That's expected. you can keep instanes alive and re-use them with the <keep-alive> component, but that's usually not necessary and if so, requires special attention to re-initiate all local state of re-used components where necesseray.

Creating a fresh instance is much cleaner and therefore the default behaviour.

Further the old instances are not deleted and are running in background!

That's not expected. Previous instances are destroyed.

setInterval(() => {console.log('Instance ' + this._uid + ' of Foo is running')}, 500);

Well, since this intervall callback contains a reference to the component instance, it can't be garbage collected by the browser, So you are keeping them alive, not Vue.

Without that intervall, I woudl expect the instance to be garbage collected after the router destroyed them.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!