VUE 整合websocket 全局调用,局部监听,事件响应,自定义协议

废话不多说直接贴代码

 

1,新建一个websocketStore.js

import Vue from 'vue'
import Vuex from 'vuex'Vue.use(Vuex)export default new Vuex.Store({state: {websock: null,eventlist:[]},getters: {onEvent(state) {return function (method) {let index = state.eventlist.map((eb) => {return eb.method}).indexOf(method);if (state.eventlist.length > 0 && index >= 0) {let result = Object.assign({}, state.eventlist[index]);state.eventlist.splice(index, 1);return result.data;}return null;}}},mutations: {WEBSOCKET_INIT(state,url) {state.websock = new WebSocket(url);state.websock.onopen = function () {console.log("连接成功!");}state.websock.onmessage = function (callBack) {console.log("ws接收!");console.log(callBack.data);var receive = [];var type = 0;var length = 0;receive = receive.concat(Array.from(new Uint8Array(callBack.data)));if (receive.length < 6) {console.log("包头大小错误:" + receive.length)return;}var index = 0;type = new DataView(new Uint8Array(receive).buffer).getUint16(index)index += 2;


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部