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