websocket逻辑优化

This commit is contained in:
kron
2025-07-18 13:38:01 +08:00
parent ccfd09bb01
commit 4f4178b75d
3 changed files with 42 additions and 41 deletions

View File

@@ -1,6 +1,6 @@
<script setup>
import { watch } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { onShow, onHide } from "@dcloudio/uni-app";
import websocket from "@/websocket";
import useStore from "@/store";
import { storeToRefs } from "pinia";
@@ -30,18 +30,16 @@ watch(
onShow(() => {
const token = uni.getStorageSync("token");
if (user.value.id && token) {
// 检查 WebSocket 连接状态
uni.sendSocketMessage({
data: JSON.stringify({ event: "ping", data: {} }),
fail: () => {
// 如果发送失败,说明连接已断开,需要重新连接
websocket.createWebSocket(token, (content) => {
uni.$emit("socket-inbox", content);
});
},
console.log("回到前台,重新连接 websocket");
websocket.createWebSocket(token, (content) => {
uni.$emit("socket-inbox", content);
});
}
});
onHide(() => {
websocket.closeWebSocket();
});
</script>
<style>