vue实现翻译功能
Vue 实现翻译功能的方案
使用 vue-i18n 插件
安装 vue-i18n 依赖:
npm install vue-i18n
创建语言资源文件(如 locales/en.json 和 locales/zh.json):
// en.json
{
"hello": "Hello",
"welcome": "Welcome"
}
// zh.json
{
"hello": "你好",
"welcome": "欢迎"
}
初始化 i18n 实例:
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import en from './locales/en.json'
import zh from './locales/zh.json'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: 'en', // 默认语言
messages: { en, zh }
})
new Vue({ i18n }).$mount('#app')
在模板中使用翻译:
<p>{{ $t('hello') }}</p>
<p>{{ $t('welcome') }}</p>
切换语言:
this.$i18n.locale = 'zh' // 切换到中文
动态加载语言包
对于大型项目,可以按需加载语言包:
async function loadLocaleMessages(locale) {
const messages = await import(`./locales/${locale}.json`)
i18n.setLocaleMessage(locale, messages.default)
}
浏览器语言自动检测
自动检测用户浏览器语言:
const navigatorLang = navigator.language.split('-')[0]
const supportedLangs = ['en', 'zh']
const defaultLang = supportedLangs.includes(navigatorLang) ? navigatorLang : 'en'
const i18n = new VueI18n({
locale: defaultLang,
fallbackLocale: 'en',
messages: { en, zh }
})
在组件外使用翻译
在 Vue 组件外部使用翻译功能:
import i18n from './i18n'
const translatedText = i18n.t('hello')
处理复数形式
vue-i18n 支持复数处理:
{
"apple": "no apples | one apple | {count} apples"
}
使用方式:
<p>{{ $tc('apple', 0) }}</p> <!-- 输出: no apples -->
<p>{{ $tc('apple', 1) }}</p> <!-- 输出: one apple -->
<p>{{ $tc('apple', 5) }}</p> <!-- 输出: 5 apples -->
日期和数字本地化
vue-i18n 提供本地化日期和数字处理:
const date = new Date()
const formattedDate = this.$d(date, 'short')
const number = 123456.789
const formattedNumber = this.$n(number, 'currency')
自定义翻译缺失处理
设置自定义缺失处理逻辑:
const i18n = new VueI18n({
missing: (locale, key) => {
console.warn(`Missing translation: ${key} for locale ${locale}`)
return key
}
})
与路由结合实现语言切换
在路由切换时保持语言状态:
router.beforeEach((to, from, next) => {
const lang = to.params.lang
if (lang && i18n.availableLocales.includes(lang)) {
i18n.locale = lang
}
next()
})
服务端渲染(SSR)支持
在 Nuxt.js 中使用 vue-i18n:
- 安装
nuxt-i18n模块 - 配置
nuxt.config.js:modules: [ ['nuxt-i18n', { locales: ['en', 'zh'], defaultLocale: 'en', vueI18n: { fallbackLocale: 'en' } }] ]
性能优化建议
对于大型多语言应用:
- 按需加载语言包
- 使用懒加载方式引入翻译文件
- 考虑将常用翻译缓存到本地存储
- 避免在模板中频繁调用翻译函数
替代方案
如果不使用 vue-i18n,可以考虑:
- 自定义翻译服务封装
- 使用其他国际化库如 format-message
- 集成第三方翻译 API 如 Google Translate
每种方案根据项目规模和需求选择,vue-i18n 是 Vue 生态中最成熟的国际化解决方案。







