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

本文介绍了如何在Vue项目中整合WebSocket,包括在websocketStore.js中创建连接,main.js中引入并初始化,如何发送消息,以及设置监听回调进行事件响应。通过这种方式,实现了WebSocket的全局调用和局部监听功能。
摘要由CSDN通过智能技术生成

废话不多说直接贴代码

 

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;

 
  • 9
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 17
    评论
Vue是一款流行的JavaScript框架,用于构建用户界面。它提供了一套响应式的数据驱动视图组件,以及强大的工具和插件生态系统。 要在Vue全局监听一个WebSocket连接并接收数据,我们可以使用Vue的插件机制来实现。 首先,我们需要创建一个WebSocket插件。在该插件中,我们会在Vue实例中注册一个全局事件监听器来接收数据。插件代码可以如下所示: ```javascript const WebSocketPlugin = { install(Vue, options) { // 创建WebSocket连接 const socket = new WebSocket(options.url); // 监听WebSocket的打开事件 socket.addEventListener('open', () => { console.log('WebSocket连接已打开'); }); // 监听WebSocket的错误事件 socket.addEventListener('error', (error) => { console.error('WebSocket连接出现错误', error); }); // 监听WebSocket的消息事件 socket.addEventListener('message', (event) => { // 将收到的消息作为一个全局事件触发 Vue.prototype.$globalBus.$emit('websocketMessage', event.data); }); // 在Vue实例中注册全局事件 Vue.prototype.$globalBus = new Vue(); } }; export default WebSocketPlugin; ``` 接下来,我们需要在Vue的入口文件(比如main.js)中安装该插件: ```javascript import Vue from 'vue'; import App from './App.vue'; import WebSocketPlugin from './WebSocketPlugin.js'; Vue.use(WebSocketPlugin, { url: 'ws://example.com/websocket' // WebSocket服务器的URL }); new Vue({ render: h => h(App) }).$mount('#app'); ``` 现在我们就可以在Vue组件中监听全局事件来接收WebSocket的数据了。在组件中,我们可以使用`$globalBus.$on`方法来监听事件,并在回调函数中处理接收到的数据,例如: ```javascript export default { created() { // 监听全局事件 this.$globalBus.$on('websocketMessage', this.handleWebSocketMessage); }, methods: { handleWebSocketMessage(data) { // 处理收到的WebSocket数据 console.log('收到WebSocket数据:', data); } } }; ``` 至此,我们就成功地在Vue中实现了全局监听WebSocket连接并接收数据的功能。无论在哪个组件中,只要监听全局事件,都能接收到WebSocket的数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 17
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值