把socket放到最外面

This commit is contained in:
kron
2025-06-05 21:32:15 +08:00
parent 219fdc54ad
commit 58bd5d9bb2
6 changed files with 110 additions and 73 deletions

View File

@@ -1,5 +1,5 @@
<script setup>
import { ref, onUnmounted } from "vue";
import { ref, onMounted, onUnmounted } from "vue";
import AppBackground from "@/components/AppBackground.vue";
import Header from "@/components/Header.vue";
import ShootProgress from "@/components/ShootProgress.vue";
@@ -9,7 +9,6 @@ import ScoreResult from "@/components/ScoreResult.vue";
import SButton from "@/components/SButton.vue";
import { createPractiseAPI } from "@/apis";
import { MESSAGETYPES, roundsName } from "@/constants";
import websocket from "@/websocket";
const start = ref(false);
const showScore = ref(false);
const scores = ref([]);
@@ -18,32 +17,35 @@ const practiseResult = ref({});
const power = ref(0);
const onReady = async () => {
const result = await createPractiseAPI(total);
await createPractiseAPI(total);
start.value = true;
const token = uni.getStorageSync("token");
websocket.createWebSocket(token, (content) => {
const messages = JSON.parse(content).data.updates || [];
messages.forEach((msg) => {
if (msg.constructor === MESSAGETYPES.ShootSyncMeArrowID) {
scores.value.push(msg.target);
power.value = msg.target.battery;
if (scores.value.length === total) {
showScore.value = true;
}
}
if (msg.constructor === MESSAGETYPES.ShootSyncMePracticeID) {
practiseResult.value = {
...msg.practice,
arrows: JSON.parse(msg.practice.arrows),
};
}
});
});
};
async function onReceiveMessage(content) {
const messages = JSON.parse(content).data.updates || [];
messages.forEach((msg) => {
if (msg.constructor === MESSAGETYPES.ShootSyncMeArrowID) {
scores.value.push(msg.target);
power.value = msg.target.battery;
if (scores.value.length === total) {
showScore.value = true;
}
}
if (msg.constructor === MESSAGETYPES.ShootSyncMePracticeID) {
practiseResult.value = {
...msg.practice,
arrows: JSON.parse(msg.practice.arrows),
};
}
});
}
onMounted(() => {
uni.$on("socket-inbox", onReceiveMessage);
});
onUnmounted(() => {
websocket.closeWebSocket();
uni.$off("socket-inbox", onReceiveMessage);
});
</script>