useTimeAgo.ts 1.8 KB

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