日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 Vue 正文

vue?項目中使用websocket的正確姿勢_vue.js

作者:藍胖子的多啦A夢 ? 更新時間: 2022-04-09 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

欄目分類
最近更新