ly-front/src/views/index.vue

121 lines
3.2 KiB
Vue
Raw Normal View History

2025-03-31 15:26:29 +00:00
<template>
<div id="home">
<contentData id="contentData" :signaData="signaData" :homeData="homeData" />
<map-control id="mapControl" :signaData="signaData" :homeData="homeData" />
</div>
</template>
<script>
"use script";
import mapControl from "./mapControl/index.vue";
import contentData from "./contentData/index.vue";
import { Homeview } from "@/api/home.js";
2025-04-01 16:12:21 +00:00
import * as signalR from "@microsoft/signalr";
2025-03-31 15:26:29 +00:00
export default {
name: "HomeIndex",
data() {
return {
2025-04-01 16:12:21 +00:00
signaData: [],
2025-03-31 15:26:29 +00:00
homeData: {},
2025-04-01 16:12:21 +00:00
timeInterval: null,
intervalTime: null
2025-03-31 15:26:29 +00:00
};
},
components: {
mapControl,
contentData
// whiteListForm
},
2025-04-01 16:12:21 +00:00
created() {
this.initSocket();
},
2025-03-31 15:26:29 +00:00
mounted() {
this.initHomeData();
this.timeInterval = setInterval(() => {
this.initHomeData();
2025-04-01 16:12:21 +00:00
}, 2000);
2025-03-31 15:26:29 +00:00
},
methods: {
initHomeData() {
2025-04-22 12:59:59 +00:00
Homeview({ time: new Date() }).then((res) => {
2025-03-31 15:26:29 +00:00
if (res.code === 0) {
this.homeData = res.data;
}
});
2025-04-01 16:12:21 +00:00
},
initSocket() {
let connection;
let isReconnecting = false;
let _this = this;
function establishConnection() {
if (connection) {
connection.stop().catch((err) => console.error("停止连接失败:", err));
}
let wPath = window.document.location.href;
let pathName = _this.$route.path;
let pos = wPath.indexOf(pathName);
let localhostPath = wPath.substring(0, pos);
let uploadUrl =
process.env.VUE_APP_API_URL === "/"
? localhostPath
: process.env.VUE_APP_API_URL;
connection = new signalR.HubConnectionBuilder()
2025-04-02 14:29:18 +00:00
.withUrl(uploadUrl + "/websocket", {
2025-04-01 16:12:21 +00:00
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
})
.configureLogging(signalR.LogLevel.Information)
.build();
connection.on("ReceiveMessage", function (message) {
if (JSON.parse(message).data !== "hello") {
let { data } = JSON.parse(message);
_this.signaData = data;
}
});
connection.serverTimeoutInMilliseconds = 30 * 60 * 1000;
connection
.start()
.then(() => {
console.log("连接成功!");
isReconnecting = false;
clearInterval(_this.intervalTime);
_this.intervalTime = null;
})
.catch((err) => {
console.error("连接失败:", err.toString());
if (!isReconnecting) {
reconnectWithDelay();
}
});
connection.onclose(() => {
console.log("连接关闭,正在尝试重新连接...");
if (!isReconnecting) {
reconnectWithDelay();
}
});
}
function reconnectWithDelay() {
isReconnecting = true;
_this.intervalTime = setInterval(() => {
console.log("正在尝试重新连接...");
establishConnection();
}, 5000); // 等待5秒后尝试重新连接
}
establishConnection(); // 初始化连接
2025-03-31 15:26:29 +00:00
}
},
// 页面销毁
beforeDestroy() {
clearInterval(this.timeInterval);
}
};
</script>
<style scoped lang="scss"></style>