通过 Vue3+Naive-UI 的数据表格组件为例,当已知一个录入时间,获取该数据的持续时间:
<template>
<n-data-table :columns="columns" :data="data" />
</template>
<script lang="ts" setup>
import { onMounted, ref, onDeactivated, onActivated } from 'vue';
const data = ref([
{ lrsj:'2024-12-01 12:31:40', cxsj: null},
{ lrsj:'2024-12-07 16:40:53', cxsj: null}
])
const columns = ref([
{ title: '录入时间', key: 'lrsj', ellipsis: { tooltip: true } },
{
title: '持续时间',
key: 'cxsj',
render (row: any) {
var value = row.cxsj / 1000;
var days = parseInt(value / 86400) > 0 ? parseInt(value / 86400) + "天" : "";
var hours = parseInt(value / 3600) - 24 * parseInt(value / 86400) > 0 ? parseInt(value / 3600) - 24 * parseInt(value / 86400) + "小时" : "";
var mins = parseInt((value % 3600) / 60) ? parseInt((value % 3600) / 60) + "分" : "";
var secs = isNaN(parseInt(value % 60)) ? "" : parseInt(value % 60) + "秒";
return days + hours + mins + secs;
}
},
])
const timer = ref<any>(null)
onActivated(() => {
if (!timer.value && data.value.length > 0) {
timer.value = setInterval(() => {
data.value.forEach((item:any) => {
item.cxsj = Date.now() - new Date(item.lrsj).getTime()
});
}, 1000);
}
})
onDeactivated(() => {
if (timer.value) {
clearInterval(timer.value);
timer.value = null;
}
})
onMounted(() => {
initData()
})
function initData(){
if (timer.value) {
clearInterval(timer.value);
timer.value = null;
}
if (!timer.value && data.value.length > 0) {
timer.value = setInterval(() => {
data.value.forEach((item:any) => {
item.cxsj = Date.now() - new Date(item.lrsj).getTime()
});
}, 1000);
}
}
</script>
若使用的是Vue2,进入、离开页面的方法需要使用beforeRouteEnter()、beforeRouteLeave,具体查看:
【Vue2】清除定时器后定时器仍在运行