vue3+ts+Vuex中如何使用websocket协议本文作者使用了ts+vue3的setup语法糖,大家注意使用的vue版本!import{createStore}from'vuex'import{stateInt}from'../interface/storeInterface'conststate:stateInt={//推送消息数据:{},webSocket:null,}exportdefaultcreateStore({state,mutations:{//websocket初始化initWebsocket(state){state.webSocket=newWebSocket(//这里填写你要连接的ws地址'ws://127.0.0.1:3000/socket/'+Math.random())//建立连接state.webSocket.onopen=function(){/**连接成功**/console.log('communicationstarted')//发送心跳防止ws协议自动断开setInterval(()=>{state.webSocket.send('1')},1000*60)}//接收服务器消息state.webSocket.onmessage=function(e){/**接收到消息时的回调函数**/console.log('Receiveddata:',e.data)//如果数据对象是字符串,可以转为对象格式letdata=JSON.parse(e.data)state.data=e.dataconsole.log(data)}统计e.webSocket.onerror=function(){/**通信异常**/console.log('通信异常')}state.webSocket.close=function(){/**关闭连接时的回调函数**/console.log('连接已断开')}},},actions:{},modules:{},})/interface/storeInterfacefileinterfaceinterfaceexportinterfacestateInt{data:ObjectwebSocket:WebSocket}在vue3中App.vue,语法糖格式下
