vue 实现国际化
Vue 国际化实现方法
使用 vue-i18n 插件
安装 vue-i18n 依赖:
npm install vue-i18n
在 Vue 项目中创建国际化配置文件(如 src/i18n.js):
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const messages = {
en: {
greeting: 'Hello!',
button: {
submit: 'Submit'
}
},
zh: {
greeting: '你好!',
button: {
submit: '提交'
}
}
}
const i18n = new VueI18n({
locale: 'en', // 默认语言
messages
})
export default i18n
在 main.js 中引入并挂载:
import i18n from './i18n'
new Vue({
i18n,
render: h => h(App)
}).$mount('#app')
在组件中使用
模板中使用 $t 方法:
<template>
<div>
<p>{{ $t('greeting') }}</p>
<button>{{ $t('button.submit') }}</button>
</div>
</template>
JavaScript 代码中使用:
this.$t('greeting')
切换语言
通过修改 locale 属性实现语言切换:
this.$i18n.locale = 'zh'
动态加载语言包
对于大型项目,可以按需加载语言包:
async function loadLocaleMessages(locale) {
const response = await fetch(`./locales/${locale}.json`)
return response.json()
}
// 切换语言时动态加载
async function setLocale(locale) {
if (!i18n.availableLocales.includes(locale)) {
const messages = await loadLocaleMessages(locale)
i18n.setLocaleMessage(locale, messages)
}
i18n.locale = locale
}
处理复数形式
vue-i18n 支持复数处理:
const messages = {
en: {
apple: 'apple | apples'
}
}
// 使用
$tc('apple', 1) // 'apple'
$tc('apple', 5) // 'apples'
日期时间本地化
配置日期时间格式:
const datetimeFormats = {
en: {
short: {
year: 'numeric',
month: 'short',
day: 'numeric'
}
}
}
const i18n = new VueI18n({
datetimeFormats
})
// 使用
$d(new Date(), 'short')
数字本地化
配置数字格式:
const numberFormats = {
en: {
currency: {
style: 'currency',
currency: 'USD'
}
}
}
const i18n = new VueI18n({
numberFormats
})
// 使用
$n(100, 'currency') // '$100.00'
浏览器语言自动检测
可以通过浏览器 API 检测用户首选语言:
const userLocale = navigator.language || navigator.userLanguage
const supportedLocales = ['en', 'zh']
const locale = supportedLocales.includes(userLocale) ? userLocale : 'en'
i18n.locale = locale
路由结合国际化
在路由路径中添加语言前缀:
const router = new VueRouter({
routes: [
{
path: '/:lang',
component: App,
children: [
// 其他路由
]
}
]
})
在路由守卫中同步语言状态:
router.beforeEach((to, from, next) => {
const lang = to.params.lang
if (i18n.availableLocales.includes(lang)) {
i18n.locale = lang
}
next()
})






