VUE中优雅的全局使用websocket
1.首先创建一个全局 js 文件,如 global.js ,用于定义全局变量 ws 和方法 setWs()
export default {
ws: {},
setWs: function(newWs) {
this.ws = newWs
}
}
在 main.js 中引入 global.js
import global from './xx/global.js'
Vue.prototype.$global = global
在 app.vue 中初始化 webSocket ,并在 created() 方法中调用
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() {
console.log("连接已关闭...");
setTimeout(() => {
that.localSocket();
}, 2000);
};
} else {
console.log("您的浏览器不支持 WebSocket!");
}
},
在其他页面发送和接收 socket 消息
在其他页面发送和接收 socket 消息
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);
};
}