显示相对时间的组件,如"刚刚"、"5 分钟前"、"昨天"等。
<template>
<FmTimeAgo :date="new Date()" />
</template><template>
<FmTimeAgo :date="new Date()" :show-second="true" />
</template><template>
<FmTimeAgo
:date="postDate"
:messages="{
justNow: '刚刚发布',
past: n => `${n}之前`,
hour: n => `${n}个小时`,
minute: n => `${n}分钟`,
}"
/>
</template>| 参数 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| date | 日期对象 | Date | new Date() |
| max | 最大单位 | UseTimeAgoUnitNamesDefault | undefined |
| messages | 自定义消息 | UseTimeAgoMessages | 中文默认配置 |
| showSecond | 是否显示秒 | boolean | false |
| updateInterval | 更新间隔 (ms) | number | 30000 |
{
justNow: '刚刚',
past: n => `${n}前`,
future: n => `${n}后`,
month: (n, past) => n === 1 ? (past ? '上个月' : '下个月') : `${n} 月`,
year: (n, past) => n === 1 ? (past ? '去年' : '明年') : `${n} 年`,
day: (n, past) => n === 1 ? (past ? '昨天' : '明天') : `${n} 天`,
week: (n, past) => n === 1 ? (past ? '上周' : '下周') : `${n} 周`,
hour: n => `${n} 小时`,
minute: n => `${n} 分钟`,
second: n => `${n} 秒`,
invalid: '',
}<script setup lang="ts">
const postDate = new Date('2024-01-15 10:30:00')
</script>
<template>
<article>
<h1>文章标题</h1>
<div class="text-sm text-muted-foreground">
发表于 <FmTimeAgo :date="postDate" />
</div>
</article>
</template><template>
<div class="space-y-4">
<div v-for="comment in comments" :key="comment.id">
<div class="flex items-center gap-2">
<img :src="comment.avatar" class="w-8 h-8 rounded-full" />
<span class="font-bold">{{ comment.author }}</span>
<span class="text-sm text-muted-foreground">
<FmTimeAgo :date="comment.createdAt" />
</span>
</div>
<p class="mt-2">{{ comment.content }}</p>
</div>
</div>
</template><template>
<!-- 最大显示到"天" -->
<FmTimeAgo :date="oldDate" max="day" />
<!-- 输出:3 天前(而不是 3 天 5 小时前) -->
</template><script setup lang="ts">
// 每 5 秒更新一次
const now = ref(new Date())
onMounted(() => {
setInterval(() => {
now.value = new Date()
}, 5000)
})
</script>
<template>
<div>
当前时间:<FmTimeAgo :date="now" :update-interval="5000" />
</div>
</template>