直接上代码,用了element给的样例做数据,关键点是处理数据里面增加了定时器。
<template>
<div>
<el-table :data="tableData"
style="width: 100%">
<el-table-column prop="name"
label="姓名"
width="180">
</el-table-column>
<el-table-column prop="address"
label="地址">
</el-table-column>
<el-table-column prop="date"
label="日期"
width="180">
</el-table-column>
<el-table-column prop="date"
label="倒计时"
width="180">
<template slot-scope="scope">
{{ timeFormat(scope.row.lastTime) }}
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
export default {
name: "Test",
data: function () {
return {
tableData: [
{
date: "2021-09-17 16:03:20",
name: "王小虎",
address: "上海市普陀区金沙江路 1518 弄",
lastTime: 0,
},
{
date: "2021-09-17 15:03:20",
name: "王小虎",
address: "上海市普陀区金沙江路 1517 弄",
lastTime: 0,
},
{
date: "2021-09-17 12:03:20",
name: "王小虎",
address: "上海市普陀区金沙江路 1519 弄",
lastTime: 0,
},
{
date: "2021-09-17 10:03:20",
name: "王小虎",
address: "上海市普陀区金沙江路 1516 弄",
lastTime: 0,
},
],
};
},
created() {
// 从后端获取的数据,将这一步骤放到异步获取后端数据的地方,对后端返回的数据进行处理
this.tableData.forEach((ele) => {
//调用定时器传递
this.daojishi(ele);
// 如果数据不更新的话,增加下面代码
// this.tableData.splice(1, 0);
});
},
methods: {
// 倒计时定时器
daojishi(row) {
// 绑定定时器
row.countDown = setInterval(() => {
// 计算剩余时间戳
let residue = new Date(row.date).getTime() - new Date();
if (residue > 0) {
// 对每行的剩余时间进行设置
row.lastTime = residue;
} else {
// 清除定时器
clearInterval(row.countDown);
}
}, 1000);
},
// 剩余时间格式化
timeFormat(times) {
if (times > 0) {
let days = this.addZero(
Math.floor(times / 1000 / 60 / 60 / 24)
); //天
let hours = this.addZero(
Math.floor((times / 1000 / 60 / 60) % 24)
); //时
let minutes = this.addZero(
Math.floor((times / 1000 / 60) % 60)
); //分
let seconds = this.addZero(Math.floor((times / 1000) % 60)); //秒
return `${days}天${hours}小时${minutes}分钟${seconds}秒`;
} else {
return "已超时";
}
},
// 个位补零
addZero(d) {
return parseInt(d) < 10 ? "0" + d : d;
},
},
};
</script>