sh_real_name_system_web/src/views/warning/AlertNotification.vue

127 lines
3.2 KiB
Vue
Raw Normal View History

2025-08-04 16:09:05 +08:00
<template>
<div id="app">
<h2>告警系统</h2>
<p v-if="isConnected">WebSocket 已连接</p>
<p v-else>WebSocket 连接中...</p>
</div>
</template>
<script>
import { MessageBox } from 'element-ui';
export default {
data() {
return {
socket: null,
wsUrl: 'ws://localhost:18082/ws', // WebSocket 端点
isConnected: false, // 连接状态
reconnectInterval: 5000 // 自动重连时间间隔(毫秒)
};
},
created() {
// 页面加载时自动连接 WebSocket
this.connectWebSocket();
},
methods: {
// 连接 WebSocket
connectWebSocket() {
if (this.socket) {
console.log("WebSocket 已连接");
return;
}
this.socket = new WebSocket(this.wsUrl);
// 监听 WebSocket 连接成功事件
this.socket.onopen = () => {
console.log("WebSocket 连接成功");
this.isConnected = true;
};
// 接收消息
this.socket.onmessage = (event) => {
console.log("收到消息:", event.data);
const warning = JSON.parse(event.data);
this.handleWarning(warning);
};
// 监听连接关闭事件
this.socket.onclose = () => {
console.log("WebSocket 连接已关闭");
this.isConnected = false;
this.socket = null;
// 自动重连
this.reconnectWebSocket();
};
// 监听连接错误事件
this.socket.onerror = (error) => {
console.error("WebSocket 错误:", error);
this.isConnected = false;
this.socket = null;
// 自动重连
this.reconnectWebSocket();
};
},
// 自动重连 WebSocket
reconnectWebSocket() {
console.log("尝试重新连接 WebSocket...");
setTimeout(() => {
this.connectWebSocket();
}, this.reconnectInterval);
},
// 处理告警信息并显示弹窗
handleWarning(warning) {
const { warningEvent, warningContent, warningGrade, warningIp, warningTime } = warning;
const formattedTime = new Date(warningTime).toLocaleString();
// 弹出告警信息
MessageBox.alert(
`
<p><strong>事件</strong>${warningEvent}</p>
<p><strong>内容</strong>${warningContent}</p>
<p><strong>等级</strong>${warningGrade}</p>
<p><strong>IP</strong>${warningIp}</p>
<p><strong>时间</strong>${formattedTime}</p>
`,
'告警通知',
{
dangerouslyUseHTMLString: true,
confirmButtonText: '确认',
callback: () => {
this.notifyBackend(warning.warningId);
}
}
);
},
// 通知后端告警已处理
notifyBackend(warningId) {
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
const message = {
warningId,
status: '1' // 1 表示已处理
};
this.socket.send(JSON.stringify(message));
console.log(`已通知后端处理告警: ${warningId}`);
}
}
},
beforeDestroy() {
// 页面销毁时关闭 WebSocket 连接
if (this.socket) {
this.socket.close();
}
}
};
</script>
<style scoped>
#app {
text-align: center;
margin-top: 50px;
}
</style>