Files
Situation-Awareness-Platfor…/src/components/Time/index.vue

48 lines
965 B
Vue
Raw Normal View History

2025-03-12 18:41:20 +08:00
<template>
{{ timeStr }}
</template>
<script setup lang="ts">
import { ref, Ref, onBeforeUnmount, onMounted, watch } from 'vue';
import { useTimeFormat } from '@/utils/hooks/useTimeFormat';
interface IProps {
time: string | number,
interval?: number
}
const props = withDefaults(defineProps<IProps>(), {
interval: 60 // 默认刷新间隔单位s
});
const timeStr: Ref<string> = ref('-');
const { formatTimeFromNow } = useTimeFormat();
const init = (): void => {
let timeout: number | undefined;
const updateTime = (): void => {
try {
timeStr.value = formatTimeFromNow(props.time);
clearTimeout(timeout);
timeout = setTimeout(() => {
updateTime();
}, props.interval * 1000);
} catch (err) {
// ignore
}
};
onBeforeUnmount(() => {
clearTimeout(timeout);
timeout = undefined;
});
updateTime();
watch(() => props.time, updateTime);
};
onMounted(() => {
init();
});
</script>