一,使用vuex存储websocket获取的数据src/store/index
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
wsData:{},
},
mutations: {
setWebSocket(state,data){
state.wsData = data;
}
},
actions: {
},
modules: {
}
})
二,在untils下创建websocket.js
import ElementUI from "element-ui";
import store from '../store/index';
function initWebSocket(WS_API) {
const wsUri = WS_API;
this.socket = new WebSocket(wsUri); //这里面的this都指向vue
this.socket.onopen = websocketOnOpen;
this.socket.onerror = webSocketOnError;
this.socket.onmessage = webSocketOnMessage;
this.socket.onclose = closeWebsocket;
}
function webSocketOnError(e) {
ElementUI.Notification({
title: "",
message: "WebSocket连接发生错误" + e,
type: "error",
duration: 0,
});
}
function websocketOnOpen() {
console.log("websocketOnOpen");
}
function webSocketOnMessage(e) {
console.log("发送消息");
let data = JSON.parse(e.data);
store.commit('setWebSocket',data)
}
// 关闭websocket
function closeWebsocket() {
console.log("连接已关闭...");
}
function close() {
// this.socket.close(); // 关闭 websocket
this.socket.onclose = function(e) {
console.log(e); //监听关闭事件
console.log("关闭");
};
}
function webSocketSend() {
// 发送参数
this.socket.send();
}
export default {
initWebSocket,
webSocketSend,
close,
};
三,在main.js中注册
import webSocket from "./utils/websocket.js";
Vue.prototype.webSocket = webSocket;
四,在App.vue中
//此处许注意判断页面的路由,否则会触发两次this.init_WebSocket();
watch: {
$route: {
immediate: true, // 一旦监听到路由的变化立即执行
handler() {
let token = localStorage.getItem("token");
if (token) {
this.init_WebSocket();
}
},
},
},
mounted() {},
methods: {
init_WebSocket() {
// 允许连接的数组
let path = this.$route.path;
let path_list = ["/one"];
console.log(path);
if (path_list.includes(path)) {
let WS_API = "";
WS_API = `ws://**.***.**.**:****?type=op`;
// this.webSocket.close();
this.webSocket.initWebSocket(WS_API);
}
},
},
五,在需要调用websocket的页面
import store from "../../store/index";
//为什么要使用定时器?
//因为在使用组件后无法获取到websocket更新的数据
mounted() {
this.getData();
this.timer = setInterval(() => {
this.get_websocket();
}, 3000);
this.$once("hook:beforeDestroy", function() {
clearInterval(this.timer);
});
},
methods:{
// 数据处理
// 如果websocket和getData使用的是同一组数据,那么在get_Data之后需要使用store.commit('setWebSocket',data)更新缓存中的数据
datamation(wsData) { },
get_websocket() {
let webSocket_data = store.state.wsData || {};
//判断是否为空对象
let arr = Object.keys(webSocket_data);
if (arr.length > 0) {
this.datamation(webSocket_data);
}
},
get_data(){
//store.commit('setWebSocket',data)
}
}
参考文章:https://www.php.cn/blog/detail/32552.html
备注:使用vuex和定时器实非得已,欢迎大家指出更好的办法一起讨论