vue 项目中使用websocket的正确姿势
作者:蓝胖子的多啦A梦
这篇文章主要介绍了vue 项目中使用websocket的实例代码,通过实例代码给大家介绍了在utils下新建websocket.js文件的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
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
}

如果想刷新重新链接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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
您可能感兴趣的文章:
- 一文详解websocket在vue2中的封装使用
- Vue项目中Websocket的使用实例
- 前端之vue3使用WebSocket的详细步骤
- vue3.0中使用websocket,封装到公共方法的实现
- vue3+ts+Vuex中使用websocket协议方式
- Vue项目使用Websocket大文件FileReader()切片上传实例
- vue项目使用websocket连接问题及解决
- Vue websocket封装实现方法详解
- vue使用websocket概念及示例
- vue基于websocket实现智能聊天及吸附动画效果
- Flask使用SocketIO实现WebSocket与Vue进行实时推送
- vue+flv.js+SpringBoot+websocket实现视频监控与回放功能
- vue项目中使用websocket的实现
- vue实现websocket客服聊天功能
- Vue+Websocket简单实现聊天功能
- vue使用WebSocket模拟实现聊天功能
- websocket+Vuex实现一个实时聊天软件
- 使用WebSocket + SpringBoot + Vue 搭建简易网页聊天室的实现代码
