温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vue中怎么使用websocket

发布时间:2022-01-28 09:10:06 来源:亿速云 阅读:403 作者:iii 栏目:开发技术

这篇文章主要介绍“vue中怎么使用websocket”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“vue中怎么使用websocket”文章能帮助大家解决问题。

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连接发生错误" + 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
}

vue中怎么使用websocket

vue中怎么使用websocket

如果想刷新重新链接websocket 可以在App.vue页面里添加个钩子函数

 mounted() {
    //当在任一路由页面被刷新时,便是根组件app被从新建立,此时能够进行webSocket重连
    //从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”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI