useTimeAgo.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { useTimeAgo as useTimeAgoCore, UseTimeAgoMessages } from '@vueuse/core'
  2. import { computed, unref } from 'vue'
  3. import { useLocaleStoreWithOut } from '@/store/modules/locale'
  4. const TIME_AGO_MESSAGE_MAP: {
  5. 'zh-CN': UseTimeAgoMessages
  6. en: UseTimeAgoMessages
  7. } = {
  8. 'zh-CN': {
  9. justNow: '刚刚',
  10. past: (n) => (n.match(/\d/) ? `${n}前` : n),
  11. future: (n) => (n.match(/\d/) ? `${n}后` : n),
  12. month: (n, past) => (n === 1 ? (past ? '上个月' : '下个月') : `${n} 个月`),
  13. year: (n, past) => (n === 1 ? (past ? '去年' : '明年') : `${n} 年`),
  14. day: (n, past) => (n === 1 ? (past ? '昨天' : '明天') : `${n} 天`),
  15. week: (n, past) => (n === 1 ? (past ? '上周' : '下周') : `${n} 周`),
  16. hour: (n) => `${n} 小时`,
  17. minute: (n) => `${n} 分钟`,
  18. second: (n) => `${n} 秒`
  19. },
  20. en: {
  21. justNow: 'just now',
  22. past: (n) => (n.match(/\d/) ? `${n} ago` : n),
  23. future: (n) => (n.match(/\d/) ? `in ${n}` : n),
  24. month: (n, past) =>
  25. n === 1 ? (past ? 'last month' : 'next month') : `${n} month${n > 1 ? 's' : ''}`,
  26. year: (n, past) =>
  27. n === 1 ? (past ? 'last year' : 'next year') : `${n} year${n > 1 ? 's' : ''}`,
  28. day: (n, past) => (n === 1 ? (past ? 'yesterday' : 'tomorrow') : `${n} day${n > 1 ? 's' : ''}`),
  29. week: (n, past) =>
  30. n === 1 ? (past ? 'last week' : 'next week') : `${n} week${n > 1 ? 's' : ''}`,
  31. hour: (n) => `${n} hour${n > 1 ? 's' : ''}`,
  32. minute: (n) => `${n} minute${n > 1 ? 's' : ''}`,
  33. second: (n) => `${n} second${n > 1 ? 's' : ''}`
  34. }
  35. }
  36. export const useTimeAgo = (time: Date | number | string) => {
  37. const localeStore = useLocaleStoreWithOut()
  38. const currentLocale = computed(() => localeStore.getCurrentLocale)
  39. const timeAgo = useTimeAgoCore(time, {
  40. messages: TIME_AGO_MESSAGE_MAP[unref(currentLocale).lang]
  41. })
  42. return timeAgo
  43. }