如何为Vuex WebSocket插件添加可在action中调用的消息发送函数
问题原因
- 你没有在Vuex文件中导入插件暴露的
sendWebSocketMsg方法,所以调用时报错找不到函数 - 原生WebSocket实例发送消息的API是
send(),不是你写的sendMsg(),属于API拼写错误
第一步:修改WebSocket插件代码
把插件的导出逻辑修正,同时修正API调用错误,修改后完整代码如下:
var store = null; var ws = null; function startWebsocket() { ws = new WebSocket(process.env.VUE_APP_WEBSOCKET_URL) ws.onmessage = function (event) { console.log("webSocket: on message: ", event.data); store.dispatch('remoteMessage', event.data); } ws.onopen = function (event) { console.log("webSocket: on open: ", event) store.dispatch('connectionOpened'); } ws.onclose = function (event) { console.log("webSocket: on close: ", event) store.dispatch('connectionClosed'); ws = null setTimeout(startWebsocket, 5000) } ws.onerror = function (event) { console.log("webSocket: on error: ", event) } } // 新增的发送消息方法,修正API调用为send,额外增加连接状态判断避免报错 export function sendWebSocketMsg(msg) { if (ws && ws.readyState === WebSocket.OPEN) { ws.send(msg) } } export default function createWebSocketPlugin() { return store_param => { store = store_param; startWebsocket(); }; }
新增的ws.readyState === WebSocket.OPEN判断可以避免连接还在建立中时调用发送接口抛出异常。
第二步:修改Vuex index.js代码
导入sendWebSocketMsg方法后就可以正常调用了,修改导入部分代码:
// 原来只导入了默认导出的插件,现在新增导入命名导出的发送方法 import webSocket, { sendWebSocketMsg } from '../plugins/webSocket' // 后面的Store配置不需要改动,原有pause、play action的调用逻辑可以正常运行 export default new Vuex.Store({ // ... 你的其他配置 actions: { connectionOpened({ commit }) { commit('SET_CONNECTION', true); }, connectionClosed({ commit }) { commit('SET_CONNECTION', false); }, connectionError({ commit }, error) { commit('SET_ERROR', error); }, remoteMessage({commit}, message) { commit('SET_MESSAGE', message); }, pause() { sendWebSocketMsg('{"pause":true}') }, play() { sendWebSocketMsg('{"pause":false}') } } })
内容的提问来源于stack exchange,提问作者chmike
相关产品推荐
相关产品推荐

