相对时间可以理解为最后一次“打招呼”的时间和当前时间的差值。例如:2 小时前,1 天前,1 年前等

一、relativeTime 函数

使用 day.js 将后端返回的时间戳处理为相对时间(1 小时前,1 天前等格式)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import dayjs from "dayjs";
import rTime from "dayjs/plugin/relativeTime";
// 处理语言
import "dayjs/locale/zh-cn";
import store from "@/store";

// 时间格式处理: 2022-08-15
const dateFilter = (val, format = "YYYY-MM-DD") => {
if (!isNaN(val)) {
val = parseInt(val);
}
return dayjs(val).format(format);
};

// 加载相对时间插件
dayjs.extend(rTime);
// 相对时间处理
function relativeTime(val) {
if (!isNaN(val)) {
val = parseInt(val);
}
return dayjs()
.locale(store.getters.langeage === "zh" ? "zh-cn" : "en")
.to(dayjs(val));
}

export default (app) => {
app.config.globalProperties.$filters = {
dateFilter,
relativeTime,
};
};

app.config.globalProperties 是挂载在 vue 实例上面的,所以可以直接在 template 里面访问

二、组件内处理为相对时间

1
2
3
4
5
6
7
8
9
10
11
12
13
<el-table ref="tableRef" :data="tableData" border>
<el-table-column
v-for="(item, index) in tableColumns"
:key="index"
:prop="item.prop"
:label="item.label"
>
// 相对时间的处理
<template #default="{ row }" v-if="item.prop === 'publicDate'">
{{ $filters.relativeTime(row.publicDate) }}
</template>
</el-table-column>
</el-table>