NetworkConnectionState.vue
1 <script setup> 2 import { computed, onMounted, onUnmounted, ref } from 'vue' 3 import StateIndicator from './StateIndicator.vue' 4 5 const props = defineProps({ 6 connectionTest: { 7 type: Function, 8 required: true 9 }, 10 text: { 11 type: String, 12 required: true 13 } 14 }) 15 16 const isAlive = ref(true) 17 const loading = ref(false) 18 const color = computed(() => { 19 if (loading.value === true) return 'yellow' 20 else if (isAlive.value === true) return 'green' 21 else return 'red' 22 }) 23 let checkIntervalId 24 25 async function checkConnection() { 26 loading.value = true 27 try { 28 isAlive.value = await props.connectionTest() 29 } catch (e) { 30 isAlive.value = false 31 } finally { 32 loading.value = false 33 } 34 } 35 36 onMounted(() => { 37 checkConnection() 38 checkIntervalId = setInterval(() => { 39 checkConnection() 40 }, 5000) 41 }) 42 43 onUnmounted(() => { 44 clearInterval(checkIntervalId) 45 }) 46 </script> 47 48 <template> 49 <StateIndicator size="sm" :color="color" :text="text"></StateIndicator> 50 </template>