let startTime = ref(null) let timer = ref(null) let currentTime: any = ref('') onMounted(() => { // 获取初始时间戳 getInitialTimestamp(); // 设置定时器,每秒更新当前时间 timer.value = setInterval(() => { updateCurrentTime(); }, 1000); }) onBeforeUnmount(() => { clearInterval(timer.value); // 组件卸载前清除定时器 }) // 获取初始时间戳 async function getInitialTimestamp() { const id = window.localStorage.getItem('RowID'); try { const RunningTimeData = await api.RunningTime(id); const { data: res } = RunningTimeData; console.log('运行时间', res); const startTimeItem = res.data; startTime.value = startTimeItem; // 保存初始时间戳 updateCurrentTime(); // 第一次调用更新时间的函数 } catch (error) { console.error('获取初始时间戳失败:', error); } } // 更新当前时间 function updateCurrentTime() { if (startTime.value !== null) { const timestamp = Date.now() - startTime.value; // 计算已经过去的时间 currentTime.value = convertTimestampToTime(timestamp); // 转换为日、时、分、秒格式 } } // 时间戳转换函数 function convertTimestampToTime(timestamp) { const days = Math.floor(timestamp / (1000 * 60 * 60 * 24)); // 计算天数 const hours = Math.floor((timestamp % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); // 计算小时 const minutes = Math.floor((timestamp % (1000 * 60 * 60)) / (1000 * 60)); // 计算分钟 const seconds = Math.floor((timestamp % (1000 * 60)) / 1000); // 计算秒数 // 格式化处理 const formattedTime = days + '天 ' + hours + '小时 ' + minutes + '分钟 ' + seconds + '秒'; return formattedTime; }