我正在使用带有Laravel Echo的Pusher为我的应用程序中的某些区域创建状态通道。我所有的前端路由都是使用Vue Router完成的。
在路由之间切换时,Vue路由器将根据我的路由设置加载某些组件。效果很好,但是Pusher不会自动将用户从这些频道断开。仅当我运行整页刷新时才会发生,这不是我想要的。
在我的组件中,加入Pusher通道的js代码在内部mounted
,如下所示:
data() {
return {
users: [],
}
},
mounted() {
Echo.join('transaction.' + this.tid)
.here(users => {
this.users = users;
}
})
.joining(user => {
this.users.push(user);
})
.leaving(user => {
this.users.splice(this.users.indexOf(user), 1);
});
},
methods: {
// ...
},
如何在不刷新页面的情况下使用Vue Router路由断开用户与频道的连接?
谢谢。
我相信Vue Router可能会出于性能原因而使组件实例保持活动状态。因此,即使在组件之间路由时,websocket通道仍然可以连接。
为避免此问题,您可以使用Vue的componentdestroyed
方法手动离开频道。
由于您正在使用Laravel的Echo,因此您所需要做的就是: Echo.leave('channel-name')
...
methods: {
// ...
},
destroyed() {
Echo.leave('transaction.' + this.tid);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句