vuex 文件中有如下函数。
当我使用 Vue 组件的“按钮”运行启动功能时,
socket.emit 将数据发送到 nodejs 的 socker。
它通过 nodejs 的 websocket 通过 socket.on 接收一些结果。
// In vuex.js
const actions = {
start(event) {
socket.emit("voice", {
msg: event.currentTarget.message
});
socket.on("voice-reply", result => {
console.log(result);
});
}
但是当我用 vuejs 的按钮运行这个启动函数时,
socket.on("voice-reply") 再重复一次。
例如,
console.log(result)
点击按钮后,
console.log(result)
console.log(result)
点击按钮后,
console.log(result)
console.log(result)
console.log(result)
它是这样运行的。您能解释一下为什么 socket.on 会增加一次运行吗?
非常感谢您阅读。
最佳答案
socket.on
创建一个 eventListener
,它会在每次发出事件时触发。通过在 start
操作中包含 socket.on
,每次调用 start
时都会创建一个新的 eventListener
(通过单击按钮),每个监听器都会记录到控制台。您不应该在发出事件的同一 block 中创建监听器。
创建一个新的 Action ,如 setupListeners
并只从其他地方调用一次,可能在您的组件中(例如在 created
生命周期 Hook 中)或从其他 Action :
const actions = {
start(event) {
socket.emit("voice", {
msg: event.currentTarget.message
});
},
setupListeners() {
socket.on("voice-reply", result => {
console.log(result);
});
}
}
关于javascript - websocket 的 Emit 在 vuejs 和 vuex 上重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59226321/