vue 语言包实现
Vue 语言包实现方法
使用 vue-i18n 插件
安装 vue-i18n 插件:
npm install vue-i18n
创建语言包文件,例如 locales/en.json 和 locales/zh.json:
// en.json
{
"welcome": "Welcome",
"hello": "Hello, {name}"
}
// zh.json
{
"welcome": "欢迎",
"hello": "你好, {name}"
}
在 Vue 项目中配置 vue-i18n:
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const messages = {
en: require('./locales/en.json'),
zh: require('./locales/zh.json')
}
const i18n = new VueI18n({
locale: 'en', // 默认语言
messages
})
new Vue({
i18n,
render: h => h(App)
}).$mount('#app')
在组件中使用语言包
模板中使用:
<template>
<div>
<p>{{ $t('welcome') }}</p>
<p>{{ $t('hello', { name: 'John' }) }}</p>
</div>
</template>
脚本中使用:
this.$t('welcome')
切换语言
this.$i18n.locale = 'zh'
动态加载语言包
对于大型项目,可以按需加载语言包:

async function loadLocaleMessages(locale) {
const messages = await import(`@/locales/${locale}.json`)
i18n.setLocaleMessage(locale, messages.default)
return nextTick()
}
命名空间
对于模块化语言包,可以使用命名空间:
// en.json
{
"login": {
"title": "Login",
"button": "Sign In"
}
}
使用时:
{{ $t('login.title') }}
复数形式处理
语言包中可以定义复数规则:
{
"apple": "no apples | one apple | {count} apples"
}
使用时:

{{ $tc('apple', 5) }}
日期和货币本地化
vue-i18n 支持日期和货币格式化:
const dateTimeFormats = {
en: {
short: {
year: 'numeric',
month: 'short',
day: 'numeric'
}
}
}
const i18n = new VueI18n({
dateTimeFormats
})
使用时:
{{ $d(new Date(), 'short') }}
最佳实践
- 将语言包按功能模块拆分
- 为翻译键使用有意义的命名
- 避免在翻译文本中包含变量
- 为所有可见文本添加翻译
- 考虑使用 CI/CD 流程自动化翻译管理
替代方案
对于不想使用 vue-i18n 的情况,可以创建简单的自定义语言系统:
const translations = {
en: { welcome: 'Welcome' },
zh: { welcome: '欢迎' }
}
Vue.prototype.$translate = function(key) {
return translations[this.$store.state.locale][key]
}






