如何格式化日期、货币等本地化内容?
解读
面试官问“如何格式化日期、货币等本地化内容”,并不是想听一句“用 Day.js 或 Intl”就结束。
在国内真实业务场景里,Vue 项目往往要同时满足:
- 设计稿给出的中文显示习惯(如 2024年05月28日 14:08、¥1,234.56)。
- 运营随时要求“英文站、日文站”秒切换。
- 服务端返回的是 Unix 时间戳或“分”单位、前端要转“元”并带千分位。
- 不能等后端接口,否则 SEO 与白屏时间不可接受。
因此,面试官想确认:
- 你是否知道 Vue 的“视图无侵入”原则——不在模板里手写
.replace(/(\d)(?=(\d{3})+\.)/g, '$1,')。 - 你是否能把国际化(i18n)与本地化(l10n)分层:语言包只管文案,格式规则交给专业 API。
- 你是否能给出“可 Tree-Shaking、可 SSR、可单元测试”的落地代码,而不是贴一个 moment.js 把包体积干到 200 kB。
知识点
- ECMAScript 原生 Intl 对象
- Intl.DateTimeFormat(locale, options)
- Intl.NumberFormat(locale, options)
优点:浏览器自带、零依赖、支持农历/伊斯兰历、货币符号自动映射。
- Vue3 组合式工具函数
- 用
computed(() => new Intl...)做派生数据,避免重复实例化。 - 用
provide/inject把 locale 下沉,保持根组件切换语言后子孙自动刷新。
- 用
- 自定义全局属性
app.config.globalProperties.$formatDate = (ts, opt) => ...- 配合
getCurrentInstance()在<script setup>里解构$formatDate,保持模板简洁。
- 与 Vue I18n v9 的协作
- 把
Intl.*封装成datetime(calendar)和number(currency)两种消息格式,
语言 JSON 里只存"{ts, date, ::yyyyMMdd}"这种 ICU 模板,
换语言时无需改代码,仅切换 locale 即可。
- 把
- SSR 安全
- 服务端渲染时
new Intl必须传明确的locale(不能navigator.language),
否则 Node 端与客户端 hydrate 后 checksum 不一致直接白屏。
- 服务端渲染时
- 性能与缓存
- Intl 构造器较重,用
Map<locale, Map<pattern, Intl.*Format>>做两层缓存,
在 Vite 生产构建里可被 Rollup 摇树掉未用的语言。
- Intl 构造器较重,用
答案
下面给出一份可直接搬进国内中厂代码仓库的“最小可运行方案”,兼顾 <script setup>、TypeScript、SSR、测试。
-
安装唯一依赖(可选,仅为了类型):
pnpm add -D @formatjs/intl -
创建
src/composables/useFormat.tsimport { 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)) ) } -
货币同理,封装
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)) ) } -
在组件内使用:
<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> -
语言切换:
// 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。 -
单元测试(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 安全、可测试、可维护。
拓展思考
-
如果产品要求“相对时间”怎么办?
继续使用 Intl.RelativeTimeFormat,封装useFormatRelative(-1, 'day')输出“1 天前”,
并配合requestAnimationFrame做分钟级自动更新,避免 setInterval 内存泄漏。 -
如果低端安卓不支持
Intl.*?
用@formatjs/intl-locale和@formatjs/intl-numberformat的 polyfill,
在vite.config.ts里按browserslist动态注入,现代浏览器不会被打包。 -
如果货币精度后端返回“分”、前端要转“元”?
在useFormatCurrency里先value / 100,
同时暴露useFormatCurrencyFromFen保持语义化,避免业务组件到处/100。 -
如果要做“多币种切换”且汇率实时?
把汇率也放进 Pinia store,
useFormatCurrency(amount, currencyCode, exchangeTarget)内部先乘汇率再Intl.NumberFormat,
切换币种时整站响应,无需刷新页面。 -
如果要做“格式回写”——用户输入“1,234.50”反向解析成 1234.5?
封装parseFormattedNumber(text: string, locale: string): number,
利用Intl.NumberFormat.formatToParts逆向解析,
这样<input v-currency-input>自定义指令也能复用同一套规则,彻底 DRY。