{{ $t('message.hello') }}
{{ t('message.hello') }}
{{ $t('greeting', { name: 'John' }) }}
``` ### 3. 复数处理 ```javascript // i18n.js const messages = { en: { apple: 'apple | apples', banana: 'no bananas | one banana | {count} bananas' } } ``` ```vue{{ $tc('apple', 1) }}
{{ $tc('apple', 5) }}
{{ $tc('banana', 0) }}
{{ $tc('banana', 1) }}
{{ $tc('banana', 10, { count: 10 }) }}
``` ### 4. 日期和数字格式化 ```javascript // i18n.js const datetimeFormats = { en: { short: { year: 'numeric', month: 'short', day: 'numeric' } }, zh: { short: { year: 'numeric', month: 'short', day: 'numeric' } } } const numberFormats = { en: { currency: { style: 'currency', currency: 'USD' } }, zh: { currency: { style: 'currency', currency: 'CNY' } } } const i18n = createI18n({ // ...其他配置 datetimeFormats, numberFormats }) ``` ```vue{{ $d(new Date(), 'short') }}
{{ $n(1000, 'currency') }}
``` ## 项目实践建议 ### 1. 模块化语言文件 ``` src/ locales/ en/ common.json home.json zh/ common.json home.json ``` ```javascript // i18n.js import { createI18n } from 'vue-i18n' import enCommon from './locales/en/common.json' import zhCommon from './locales/zh/common.json' import enHome from './locales/en/home.json' import zhHome from './locales/zh/home.json' const messages = { en: { ...enCommon, ...enHome }, zh: { ...zhCommon, ...zhHome } } // 创建i18n实例... ``` ### 2. 异步加载语言包 ```javascript async function loadLocaleMessages(i18n, locale) { const messages = await import(`./locales/${locale}.json`) i18n.global.setLocaleMessage(locale, messages.default) return nextTick() } // 切换语言时 const changeLang = async (lang) => { if (!i18n.global.availableLocales.includes(lang)) { await loadLocaleMessages(i18n, lang) } locale.value = lang } ``` ### 3. 与路由结合 ```javascript router.beforeEach((to, from, next) => { const lang = to.params.lang || 'en' const i18n = useI18n() if (i18n.locale.value !== lang) { i18n.locale.value = lang } next() }) ``` ## 常见问题解决 1. **警告 "You are running the esm-bundler build of vue-i18n"**: ```javascript // vite.config.js export default defineConfig({ resolve: { alias: { 'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js' } } }) ``` 2. **TypeScript 支持**: ```typescript // src/i18n.d.ts declare module 'vue-i18n' { export interface DefineLocaleMessage { message: { hello: string } } } ``` 3. **SSR 支持**: 需要确保每个请求都有独立的 i18n 实例,避免状态共享问题。 通过以上配置和使用方法,你可以在 Vue 3 项目中高效地实现国际化功能。