websocket优化

This commit is contained in:
kron
2025-06-22 02:39:03 +08:00
parent 322f23efb4
commit d075844cb0
6 changed files with 50 additions and 22 deletions

View File

@@ -1,11 +1,12 @@
<script setup>
import { watch } from "vue";
import { watch, onMounted, onUnmounted } from "vue";
import { onShow } from "@dcloudio/uni-app";
import websocket from "@/websocket";
import useStore from "@/store";
import { storeToRefs } from "pinia";
const store = useStore();
const { user } = storeToRefs(store);
const { updateConnect } = store;
const { updateConnect, updateUser } = store;
watch(
() => user.value.id,
@@ -16,12 +17,32 @@ watch(
uni.$emit("socket-inbox", content);
});
}
if (!newVal) {
updateConnect(false);
websocket.closeWebSocket();
}
},
{
deep: false, // 如果 user 是一个对象或数组,建议开启
immediate: false, // 若想在初始化时立即执行一次回调,可开启。
}
);
onShow(() => {
const token = uni.getStorageSync("token");
if (user.value.id && token) {
// 检查 WebSocket 连接状态
uni.sendSocketMessage({
data: JSON.stringify({ event: "ping", data: {} }),
fail: () => {
// 如果发送失败,说明连接已断开,需要重新连接
websocket.createWebSocket(token, updateConnect, (content) => {
uni.$emit("socket-inbox", content);
});
},
});
}
});
</script>
<style>