原因:使用socket.emit 发送了一个事件 另一个页面scoket.on接此接收事件 在mounted初始化 当在当前页面接收正常,一旦退出该页面再次进入就会多一次接收,实则发了一次。造成这种原因是因为当前事件一直保存没有被结束
举例:
A页面
sendMsg()
{
this.$socket.emit('send_msg', {data: 1});
}
B页面 当多次往返该页面 接收函数触发次数会随着页面往返次数增加,往返两次就打印两遍,依此类推
methods:{
// mounted 注册完直接监听
receiveMsg() {
// 接收方信息
this.$socket.on('send_msg', (e) => {
console.log(e)
});
}
},
mounted(){
this.receiveMsg()// 注册
}
解决:在on之前,off该事件
B页面
methods:{
// mounted 注册完直接监听
receiveMsg() {
//先取消再监听
this.$socket.off('send_msg');
// 接收方信息
this.$socket.on('send_msg', (e) => {
console.log(e)
});
}
},
mounted(){
this.receiveMsg()// 注册
}