vue3项目websocket消息推送提醒
1、本地调式需要先在vite.config.js中配置proxy代理
proxy: {
'^/ws': {
target: 'http://测试环境ip:8081/', //测试环境
ws: true,
changeOrigin: true,
rewrite: path => path.replace(/^\/ws/, ''),
},
},
2. 封装消息提醒公共组件,新建msgNotify.vue
<template>
<div>
</div>
</template>
<script setup>
import { reactive, ref, } from "vue";
import { ElNotification } from "element-plus";
import { useStore } from "vuex";
const store = useStore();
const socketInfo = reactive({
timeoutObj: null,
websocket: null,
})
const createWebSocket = () => {
if(socketInfo.websocket===undefined || socketInfo.websocket?.readyState !== 1){
if ('WebSocket' in window) {
const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = wsProtocol + '//' + window.location.host + `/ws/您的请求地址/ 当前登录用户`;
socketInfo.websocket = new WebSocket(wsUrl);
socketInfo.websocket.onopen = websocketOnOpen;
socketInfo.websocket.onmessage = websocketOnMessage;
socketInfo.websocket.onerror = websocketOnError;
socketInfo.websocket.onclose = websocketOnClose;
} else {
console.log("当前浏览器不支持WebSocket");
}
}
};
const websocketOnOpen = () => {
console.log("WebSocket连接成功");
};
const websocketOnMessage = (e) => {
ElNotification({
title: title,
message: message,
type: 'warning',
duration: 0,
position: 'bottom-right',
customClass: 'msg-cust-notify',
offset: 20,
})
};
const websocketOnError = (err) => {
console.log("WebSocket连接发生错误" + err);
};
const websocketOnClose = () => {
console.log("WebSocket连接关闭");
setTimeout(createWebSocket, 30*1000); //30秒
};
defineExpose({
createWebSocket,
})
</script>
<style lang="scss">
.msg-cust-notify {
.el-notification--warning {
--el-notification-icon-color: var(--el-color-warning) !important;
color: var(--el-notification-icon-color) !important;
}
.el-notification--error {
--el-notification-icon-color: var(--el-color-error) !important;
color: var(--el-notification-icon-color) !important;
}
.el-notification--success {
--el-notification-icon-color: var(--el-color-success) !important;
color: var(--el-notification-icon-color) !important;
}
.el-notification--info {
--el-notification-icon-color: var(--el-color-info) !important;
color: var(--el-notification-icon-color) !important;
}
.el-notification__closeBtn {
position: absolute !important;
}
.el-notification__icon {
height: var(--el-notification-icon-size) !important;
width: var(--el-notification-icon-size) !important;
font-size: var(--el-notification-icon-size) !important;
}
}
</style>
3、在App.vue中引入这个公共组件作为子组件,watch监听路由改变,监听到路由改变,调用createWebSocket方法
<messageNotify ref="messageNotifyRef"></messageNotify>
messageNotifyRef.value.createWebSocket()
更多推荐


所有评论(0)