1. 在utils下新建websocket.js文件 // import { showInfoMsg, showErrORMsg } from '@/utils/popInfo' i
// import { showInfoMsg, showErrORMsg } from '@/utils/popInfo'
import ElementUI from 'element-ui';
function initWEBSocket(e) {
console.log(e)
const wsUri = WS_api + "/webSocket/" + e;
this.socket = new WebSocket(wsUri)//这里面的this都指向Vue
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 webSocketOnMessage(e) {
const data = JSON.parse(e.data);
console.log(data.msgType === "INFO", data.msgType === "INFO")
if (data.msgType === "INFO") {
ElementUI.Notification({
title: '',
message: data.msg,
type: 'success',
duration: 3000,
});
} else if (data.msgType === "ERROR") {
ElementUI.Notification({
title: '',
message: data.msg,
type: 'error',
duration: 0,
});
}
}
// 关闭websiocket
function closeWebsocket() {
console.log('连接已关闭...')
}
function close() {
this.socket.close() // 关闭 websocket
this.socket.onclose = function (e) {
console.log(e)//监听关闭事件
console.log('关闭')
}
}
function webSocketSend(agentData) {
this.socket.send(agentData);
}
export default {
initWebSocket, close
}
如果想刷新重新链接websocket 可以在App.vue页面里添加个钩子函数
mounted() {
//当在任一路由页面被刷新时,便是根组件app被从新建立,此时能够进行webSocket重连
//从localStorage中获取用户信息,是登陆状态则能够进行webSocket重连
let token = localStorage.getItem("token");
if (token) {
// userMessage = JSON.parse(userMessage);
this.$websocket.initWebSocket(token);
}
},
客户端主动关闭websocket 在关闭的地方触发函数就可以
loGout() {
// localStorage.clear();
localStorage.removeItem("token");
this.$websocket.close();
this.$store.dispatch("LogOut").then(() => {
location.reload();
});
},
注:$webSocket 是在main.js中全局注册了websocket.js文件
到此这篇关于vue 项目中使用websocket的文章就介绍到这了,更多相关vue使用websocket内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: vue项目中使用websocket的正确姿势
本文链接: https://www.lsjlt.com/news/164049.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0