如何格式化日期、货币等本地化内容?

解读

面试官问“如何格式化日期、货币等本地化内容”,并不是想听一句“用 Day.js 或 Intl”就结束。
在国内真实业务场景里,Vue 项目往往要同时满足:

  1. 设计稿给出的中文显示习惯(如 2024年05月28日 14:08、¥1,234.56)。
  2. 运营随时要求“英文站、日文站”秒切换。
  3. 服务端返回的是 Unix 时间戳或“分”单位、前端要转“元”并带千分位。
  4. 不能等后端接口,否则 SEO 与白屏时间不可接受。

因此,面试官想确认:

  • 你是否知道 Vue 的“视图无侵入”原则——不在模板里手写 .replace(/(\d)(?=(\d{3})+\.)/g, '$1,')。
  • 你是否能把国际化(i18n)与本地化(l10n)分层:语言包只管文案,格式规则交给专业 API。
  • 你是否能给出“可 Tree-Shaking、可 SSR、可单元测试”的落地代码,而不是贴一个 moment.js 把包体积干到 200 kB。

知识点

  1. ECMAScript 原生 Intl 对象
    • Intl.DateTimeFormat(locale, options)
    • Intl.NumberFormat(locale, options)
      优点:浏览器自带、零依赖、支持农历/伊斯兰历、货币符号自动映射。
  2. Vue3 组合式工具函数
    • 用 computed(() => new Intl...) 做派生数据,避免重复实例化。
    • 用 provide/inject 把 locale 下沉,保持根组件切换语言后子孙自动刷新。
  3. 自定义全局属性
    • app.config.globalProperties.$formatDate = (ts, opt) => ...
    • 配合 getCurrentInstance() 在 <script setup> 里解构 $formatDate,保持模板简洁。
  4. 与 Vue I18n v9 的协作
    • 把 Intl.* 封装成 datetime(calendar) 和 number(currency) 两种消息格式,
      语言 JSON 里只存 "{ts, date, ::yyyyMMdd}" 这种 ICU 模板,
      换语言时无需改代码,仅切换 locale 即可。
  5. SSR 安全
    • 服务端渲染时 new Intl 必须传明确的 locale(不能 navigator.language),
      否则 Node 端与客户端 hydrate 后 checksum 不一致直接白屏。
  6. 性能与缓存
    • Intl 构造器较重,用 Map<locale, Map<pattern, Intl.*Format>> 做两层缓存,
      在 Vite 生产构建里可被 Rollup 摇树掉未用的语言。

答案

下面给出一份可直接搬进国内中厂代码仓库的“最小可运行方案”,兼顾 <script setup>、TypeScript、SSR、测试。

  1. 安装唯一依赖(可选,仅为了类型):

    pnpm add -D @formatjs/intl
    
  2. 创建 src/composables/useFormat.ts

    import { computed, unref } from 'vue'
    import type { MaybeRef } from '@vueuse/core'
    
    const cache = new Map<string, Intl.DateTimeFormat>()
    const getDateTimeFormat = (locale: string, opt: Intl.DateTimeFormatOptions) => {
      const key = `${locale}-${JSON.stringify(opt)}`
      if (!cache.has(key)) cache.set(key, new Intl.DateTimeFormat(locale, opt))
      return cache.get(key)!
    }
    
    export function useFormatDate(
      timestamp: MaybeRef<number | Date>,
      options: MaybeRef<Intl.DateTimeFormatOptions> = { dateStyle: 'short' }
    ) {
      // 从全局注入的 locale,后面会讲
      const { locale } = useI18n() // Vue I18n 9+
      return computed(() =>
        getDateTimeFormat(unref(locale), unref(options)).format(unref(timestamp))
      )
    }
    
  3. 货币同理,封装 useFormatCurrency:

    const numberCache = new Map<string, Intl.NumberFormat>()
    const getNumberFormat = (locale: string, opt: Intl.NumberFormatOptions) => {
      const key = `${locale}-${JSON.stringify(opt)}`
      if (!numberCache.has(key)) numberCache.set(key, new Intl.NumberFormat(locale, opt))
      return numberCache.get(key)!
    }
    
    export function useFormatCurrency(
      value: MaybeRef<number>,
      currency = 'CNY'
    ) {
      const { locale } = useI18n()
      return computed(() =>
        getNumberFormat(unref(locale), {
          style: 'currency',
          currency,
          minimumFractionDigits: 2
        }).format(unref(value))
      )
    }
    
  4. 在组件内使用:

    <template>
      <time :datetime="String(ts)">{{ fmtDate }}</time>
      <span>{{ fmtMoney }}</span>
    </template>
    
    <script setup lang="ts">
    import { ref } from 'vue'
    import { useFormatDate, useFormatCurrency } from '@/composables/useFormat'
    
    const ts = ref(Date.now())
    const fmtDate = useFormatDate(ts, { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
    const fmtMoney = useFormatCurrency(1234.5) // 输出 ¥1,234.50
    </script>
    
  5. 语言切换:

    // src/plugins/i18n.ts
    import { createI18n } from 'vue-i18n'
    const i18n = createI18n({
      legacy: false,
      locale: import.meta.env.SSR ? 'zh-CN' : navigator.language, // 防止 hydrate 错误
      fallbackLocale: 'zh-CN'
    })
    export default i18n
    

    当用户点击“English”按钮执行 i18n.global.locale.value = 'en-US',所有 useFormat* 派生值自动刷新,组件无需手动 watch。

  6. 单元测试(Jest + Vue Test Utils):

    it('should format to Chinese date', () => {
      const { useFormatDate } = require('@/composables/useFormat')
      const { locale } = useI18n()
      locale.value = 'zh-CN'
      const fmt = useFormatDate(new Date('2024-05-28T14:08:00'))
      expect(fmt.value).toMatch(/2024年5月28日/)
    })
    

至此,日期、货币本地化完全解耦,包体积仅增加 <1 kB(Tree-Shaking 后),且 SSR 安全、可测试、可维护。

拓展思考

  1. 如果产品要求“相对时间”怎么办?
    继续使用 Intl.RelativeTimeFormat,封装 useFormatRelative(-1, 'day') 输出“1 天前”,
    并配合 requestAnimationFrame 做分钟级自动更新,避免 setInterval 内存泄漏。

  2. 如果低端安卓不支持 Intl.*?
    用 @formatjs/intl-locale 和 @formatjs/intl-numberformat 的 polyfill,
    在 vite.config.ts 里按 browserslist 动态注入,现代浏览器不会被打包。

  3. 如果货币精度后端返回“分”、前端要转“元”?
    在 useFormatCurrency 里先 value / 100,
    同时暴露 useFormatCurrencyFromFen 保持语义化,避免业务组件到处 /100。

  4. 如果要做“多币种切换”且汇率实时?
    把汇率也放进 Pinia store,
    useFormatCurrency(amount, currencyCode, exchangeTarget) 内部先乘汇率再 Intl.NumberFormat,
    切换币种时整站响应,无需刷新页面。

  5. 如果要做“格式回写”——用户输入“1,234.50”反向解析成 1234.5?
    封装 parseFormattedNumber(text: string, locale: string): number,
    利用 Intl.NumberFormat.formatToParts 逆向解析,
    这样 <input v-currency-input> 自定义指令也能复用同一套规则,彻底 DRY。