vue2封装的websocket(精简版)

在src目录下新建文件夹 在文件夹中新建websocket.js

// websocket.js
const WebSocketPlugin = {
  install(Vue, options) {
    const socket = new WebSocket(options.url);

    Vue.prototype.$socket = socket;

    socket.addEventListener('open', () => {
      console.log('WebSocket连接成功');
    });

    socket.addEventListener('message', (event) => {
      console.log('Received message:', event.data);
      Vue.prototype.$emit('websocket-message', event.data);
    });

    socket.addEventListener('close', (event) => {
      console.log('WebSocket连接关闭', event);
      Vue.prototype.$emit('websocket-close', event);
    });

    socket.addEventListener('error', (error) => {
      console.error('WebSocket连接错误', error);
      Vue.prototype.$emit('websocket-error', error);
    });
  },
};

export default WebSocketPlugin;

在main.js中配置

import Vue from "vue";
import App from "./App.vue";
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
import dataV from '@jiaminghi/data-view';
import router from "./router";
import store from "./store";
import api from "@/APi/index.js";
//配置websocket
import sockets from "@/APi/websocket.js";


Vue.prototype.$api = api;
//配置weibsocket
Vue.prototype.$sockets = sockets;
 

Vue.config.productionTip = false;
Vue.use(ElementUI);
Vue.use(dataV)
new Vue({
  router,
  store,
  render: (h) => h(App),
  components: { App },
}).$mount("#app");


在页面中的使用

// 建立 web socket 连接
       this.$sockets = new WebSocket('ws://127.0.0.1:6001/');
       this.$sockets.onopen = () => {
         console.log('WebSocket 连接已打开');
       };
       this.$sockets.onmessage = (event) => {
         console.log('收到消息:', event.data);
       };
       this.$sockets.onclose = () => {
         console.log('WebSocket 连接已关闭');
       };
       this.$sockets.onerror = (error) => {
         console.error('WebSocket 发生错误:', error);
       };
       setInterval(() => {
        //发送消息
       this.$sockets.send('123');
       //关闭连接
       this.$sockets.close();
        this.$sockets.onclose();

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

slilx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值