網站首頁 Vue 正文
1. 在utils下新建websocket.js文件
// 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連接發(fā)生錯誤" + 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)//監(jiān)聽關閉事件 console.log('關閉') } } function webSocketSend(agentData) { this.socket.send(agentData); } export default { initWebSocket, close }
如果想刷新重新鏈接websocket 可以在App.vue頁面里添加個鉤子函數
mounted() { //當在任一路由頁面被刷新時,便是根組件app被從新建立,此時能夠進行webSocket重連 //從localStorage中獲取用戶信息,是登陸狀態(tài)則能夠進行webSocket重連 let token = localStorage.getItem("token"); if (token) { // userMessage = JSON.parse(userMessage); this.$websocket.initWebSocket(token); } },
客戶端主動關閉websocket 在關閉的地方觸發(fā)函數就可以
logout() { // localStorage.clear(); localStorage.removeItem("token"); this.$websocket.close(); this.$store.dispatch("LogOut").then(() => { location.reload(); }); },
注:$webSocket 是在main.js中全局注冊了websocket.js文件
原文鏈接:https://blog.csdn.net/Maxueyingying/article/details/122703998
相關推薦
- 2022-06-06 python?包之?threading?多線程_python
- 2022-05-13 ERROR org.apache.hadoop.hdfs.server.datanode.DataN
- 2022-10-06 Iptables防火墻自定義鏈表實現方式_安全相關
- 2022-06-01 利用Python實現外觀數列求解_python
- 2023-03-26 WPF實現頁面的切換的示例代碼_C#教程
- 2022-05-26 Pytorch中使用ImageFolder讀取數據集時忽略特定文件_python
- 2022-04-12 【debug】PytorchStreamReader failed reading zip arch
- 2022-08-28 IntelliJ IDEA 下debugger熱加載(Hot Swap)有時候失效解決
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支