websocket逻辑优化
This commit is contained in:
18
src/App.vue
18
src/App.vue
@@ -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>
|
||||
|
||||
Reference in New Issue
Block a user