1)首先创建一个全局 js 文件,如 global.js ,用于定义全局变量 ws 和方法 setWs()

// global.js
export default {
    ws: {},
    setWs: function(newWs) {
        this.ws = newWs
    }
}

2)在 main.js 中引入 global.js

// main.js
import global from './xx/global.js'
Vue.prototype.global = global

3)在 app.vue 中初始化 webSocket ,并在 created() 方法中调用

//app.vue
localSocket() {
  let that = this;
  if ("WebSocket" in window) {
    console.log("您的浏览器支持 WebSocket!");
    
    that.ws = new WebSocket(`wss://echo.websocket.org/`);
    that.global.setWs(that.ws);
    that.ws.onopen = that.onopen();

    that.ws.onclose = function() {
      // 关闭 websocket
      console.log("连接已关闭...");
      setTimeout(() => {
        that.localSocket();
      }, 2000);
    };
  } else {
    // 浏览器不支持 WebSocket
    console.log("您的浏览器不支持 WebSocket!");
  }
},

4)在其他页面发送和接收 socket 消息

//pageA.vue

// 发送和接收消息
handdleMsg(msg) {
  let that = this;
  console.log(that.global.ws);
  if (that.global.ws && that.global.ws.readyState == 1) {
    console.log("发送信息", msg);
    that.global.ws.send(msg);
  }
  that.global.ws.onmessage = function(res) {
    console.log("收到服务器内容", res);
  };
}
Logo

前往低代码交流专区

更多推荐