1. 程式人生 > 程式設計 >vue 專案中使用websocket的正確姿勢

vue 專案中使用websocket的正確姿勢

1. 在utils下新建websocket.檔案

// 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都指向
    this.socket.onerror = webSocketOnError;
    this.socket.onmessage = webSocketOnMessage;
    this.socket.onclose = closeWebsocket;
}
function webSocketOnError(e) {
    ElementUI.Notification({
        title: ''http://www.cppcns.com
,message: "WebSocket連線發生錯誤" + e,type: 'error',duratiohttp://www.cppcns.comn: 0,}); } function webSocketOnMessage(e) { const data = JSON.parse(e.data); console.log(data.msgType === "INFO",data.msgType === "INFO") if (data.msgType === "INFOhttp://www.cppcns.com") { ElementUI.Notification({ title: '',message: data.msg,type: 'success',duration: 3000,}); } else if (data.msgType === "ERROR") { ElementUI.Notification({ title: '',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 }

vue 專案中使用websocket的正確姿勢

vue 專案中使用websocket的正確姿勢

如果想重新整理重新連結websocket 可以在App.vue頁面裡添加個鉤子函式

 mounted() {
    //當在任一路由頁面被重新整理時,便是根元件app被從新建立,此時能夠進行webSocketyqkeISV重連
    //從localStorage中獲取使用者資訊,是登陸狀態則能夠進行webSocket重連
    let token = localStorage.getItem("token");
    if (token) {
      // userMessage = JSON.parse(userMessage);
      this.$websocket.initWebSocket(token);
    }
  },

vue 專案中使用websocket的正確姿勢

客戶端主動關閉websocket 在關閉的地方觸發函式就可以

 logout() {
      // localStorage.clear();
      localStorage.removeItem("token");
      this.$websocket.close();
      this.$store.dispatch("LogOut").then(() => {
        location.reload();
      });
    },

vue 專案中使用websocket的正確姿勢

注:$webSocket 是在main.js中全域性註冊了websocket.js檔案

vue 專案中使用websocket的正確姿勢

到此這篇關於vue 專案中使用websocket的文章就介紹到這了,更多相關vue使用websocket內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!