我正在使用 vue-router用于切换页面。现在我有两个 Vue 文档:
- Page1.vue
- Page2.vue
在两个 .vue 页面中,我都使用了 mounted()
实例。在 Page1.vue 中,代码开始监听套接字连接。当我切换到 Page2 并返回到 Page1 时,它开始监听套接字连接两次。
我已经在 page2 中使用简单的 console.log('Page1.vue') 和 Page2.vue 进行了测试。当我切换页面时,它会多次执行console.log,每次切换页面时,它都会额外执行一次console.log。
我尝试只执行一次mounted()
实例中的代码,但是切换页面后,它什么也没做。
我怎样才能保证它只挂载一次,或者我是否需要在切换页面之前卸载?如果可以,我该怎么做?
Page1.vue 和 Page2.vue
<template>
// The template
</template>
<script>
var socket = io(window.SOCKET_URL, {secure: true});
export default {
mounted(){
socket.on('channel:listen', function (data) {
console.log('Page1.vue');
}
}
}
</script>
解决方案
<template>
// The template
</template>
<script>
var socket;
export default {
beforeCreate() {
socket = io(window.SOCKET_URL, {secure: true});
},
mounted(){
socket.on('channel:listen', function (data) {
console.log('Page1.vue');
}
},
beforeDestroy() {
socket.close();
},
}
</script>
最佳答案
每当你切换路由时,与前一个路由相关的组件就会被销毁。
因此,当您从 Page1 切换到 Page2 时, Page1 组件将被销毁。然后,当您重新访问与 Page1 相关的路由时,它的实例将再次创建,从而再次调用所有生命周期方法,包括 mounted()
。从哪里开始收听您的套接字。
这是 vue 的默认行为。所以要告诉 vue 不要破坏组件,请使用 <keep-alive>
.
<keep-alive>
缓存非事件组件。
所以用 keep-alive 包装你的路由器 View :
<keep-alive>
<router-view>
</router-view>
这会缓存出现在路由器 View 中的所有组件实例。
这是一个codepen .
如果你不想缓存路由器 View 中的所有路由,你可以使用 include
or exclude
<keep-alive>
上的属性.这告诉 <keep-alive>
要缓存哪些组件实例。
所以添加name
您要缓存的路由组件的属性。
//Page1 component script
export default{
name: 'page1',
...
}
<keep-alive include="page1">
<router-view></router-view>
</keep-alive>
以上代码只缓存了Page1组件
关于vue.js - 切换页面时vue router挂载两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50097334/