javascript-vue-router始终创建一个新的Component实例
作者:互联网
我在vue-router中发现了一个问题,这让我非常感动.
总是在我的路线之间切换时,会创建该组件的新实例.此外,旧实例不会被删除并在后台运行!
我希望当我打开一条路线时,旧组件将被破坏或停止运行.
有解决此问题的解决方法吗?
这是一个小提琴:https://jsfiddle.net/4xfa2f19/5885/
let foo = {
template: '<div>Foo</div>',
mounted() {
console.log('Mount Foo with uid: ' + this._uid);
setInterval(() => {console.log('Instance ' + this._uid + ' of Foo is running')}, 500);
}
};
let bar = {
template: '<div>Bar</div>',
mounted() {
console.log('Mount Bar with uid: ' + this._uid);
setInterval(() => {console.log('Instance ' + this._uid + ' of Bar is running')}, 500);
}
};
const router = new VueRouter({
routes: [
{ path: '/user/foo', component: foo },
{ path: '/user/bar', component: bar }
]
});
const app = new Vue({ router }).$mount('#app');
解决方法:
有两种方法可以解决此问题:
正确清理销毁钩
如果使用任何外部事件侦听器,例如setInterval,addEventListener等,则还需要在销毁组件时注销它们,例如:
{
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() {
...
}
}
}
使用keep-alive使组件保持活动状态
使用keepalive时,Vue会缓存您的组件,并使其在后台保持活动状态,这意味着将仅存在一个实例.如果您有大量路由,这可能会消耗更多内存
<keep-alive>
<router-view></router-view>
</keep-alive>
标签:vue-router,javascript,vue-js,routing 来源: https://codeday.me/bug/20191011/1895429.html