useTimeAgo.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { useTimeAgo as useTimeAgoCore, UseTimeAgoMessages } from '@vueuse/core'
  2. import { useLocaleStoreWithOut } from '@/store/modules/locale'
  3. const TIME_AGO_MESSAGE_MAP: {
  4. 'zh-CN': UseTimeAgoMessages
  5. en: UseTimeAgoMessages
  6. } = {
  7. // @ts-ignore
  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. // @ts-ignore
  21. en: {
  22. justNow: 'just now',
  23. past: (n) => (n.match(/\d/) ? `${n} ago` : n),
  24. future: (n) => (n.match(/\d/) ? `in ${n}` : n),
  25. month: (n, past) =>
  26. n === 1 ? (past ? 'last month' : 'next month') : `${n} month${n > 1 ? 's' : ''}`,
  27. year: (n, past) =>
  28. n === 1 ? (past ? 'last year' : 'next year') : `${n} year${n > 1 ? 's' : ''}`,
  29. day: (n, past) => (n === 1 ? (past ? 'yesterday' : 'tomorrow') : `${n} day${n > 1 ? 's' : ''}`),
  30. week: (n, past) =>
  31. n === 1 ? (past ? 'last week' : 'next week') : `${n} week${n > 1 ? 's' : ''}`,
  32. hour: (n) => `${n} hour${n > 1 ? 's' : ''}`,
  33. minute: (n) => `${n} minute${n > 1 ? 's' : ''}`,
  34. second: (n) => `${n} second${n > 1 ? 's' : ''}`
  35. }
  36. }
  37. export const useTimeAgo = (time: Date | number | string) => {
  38. const localeStore = useLocaleStoreWithOut()
  39. const currentLocale = computed(() => localeStore.getCurrentLocale)
  40. const timeAgo = useTimeAgoCore(time, {
  41. messages: TIME_AGO_MESSAGE_MAP[unref(currentLocale).lang]
  42. })
  43. return timeAgo
  44. }