项目场景:
项目中多个地方,多个页面的数据需要同一个websocket实时推送.
解决方案:
第一步,全局创建一个global.js,定义全局变量
javascript
export default {
ws: {},
setWs: function(newWs) {
this.ws = newWs
}
}
第二步,在main.js中引入global.js,并将global的文件挂载在vue实例上
javascript
import global from "./utils/global.js";
Vue.prototype.$global = global
第三步,在入口也或者你的项目首页中初始化websocket,并在create()中调用
以app.vue为例
javascript
created() {
//获取webscoket地址
axios.get("/js/mapconfig.json").then((res) => {
const { wsUrl } = res.data;
const wsURL=wsUrl+this.UUID;//ws地址 UUID是随机数,我们需要链接上之后保持一致,将其存在vuex中
this.localSocket(wsURL)
});
},
methods:{
// 初始化 webSocket
localSocket(url) {
// return
let that = this;
if ("WebSocket" in window) {
that.ws = new WebSocket(url);
that.$global.setWs(that.ws);
that.ws.onclose = function() {
// 关闭 websocket
setTimeout(() => {
that.localSocket(url);
}, 2000);
};
} else {
// 浏览器不支持 WebSocket
console.log("您的浏览器不支持 WebSocket!");
}
},
}
mapconfig.json的文件,在public/js下新建mapconfig.json,这样是vue出包后在dist包中能实时改地址
javascript
{
"wsUrl":"ws:\\123.58.106.147:20232/ws/connect/",
}
第四步,在需要发送消息的页面调用发送消息接口
javascript
mounted(){
let data = {
"snCode":this.taskSessData.droneId,
"moduleCode":"HOME_LINK",
"open":true,//open:打开驾驶舱时传true 关闭时传false
'id':this.UUId,
};
this.handdleMsg(data)
},
methods:{
// 发送和接收消息
handdleMsg(data) {
let that = this;
if (that.$global.ws && that.$global.ws.readyState == 1) {
that.$global.ws.send(JSON.stringify(data));
}
that.$global.ws.onmessage = function(res) {
const resData=JSON.parse(res.data);
// moduleCode=="HOME_DATA"是驾驶舱飞行数据 HOME_VIDEO是驾驶舱视频流数据 HOME_WEB_MAP地图信息入口
if (resData.moduleCode=="HOME_DATA") {
that.FlightData=resData;
// 更新飞机的在线离线状态
that.$store.commit('setConnectStatusV',that.FlightData.connectStatus)
}
if (resData.moduleCode=="HOME_VIDEO") {
that.videoData=resData.videoList;
}
if (resData.moduleCode=="HOME_WEB_MAP") {
that.mapData=resData;
}
};
},
}
离开此页面发送关闭消息
javascript
destroyed() {
let data = {
"snCode":this.taskSessData.droneId,
"moduleCode":"HOME_LINK",
"open":false,//open:打开驾驶舱时传true 关闭时传false
'id':this.UUId,
};
this.handdleMsg(data)
},