vue实现中英切换
国际化(i18n)方案
Vue 中实现中英切换通常采用 vue-i18n 库,以下是具体实现步骤:
安装依赖:
npm install vue-i18n
配置多语言文件
创建语言资源文件,例如:
// en.json
{
"welcome": "Welcome",
"button": {
"submit": "Submit"
}
}
// zh-CN.json
{
"welcome": "欢迎",
"button": {
"submit": "提交"
}
}
初始化 i18n 实例
在 Vue 项目中初始化国际化插件:
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const messages = {
en: require('./locales/en.json'),
'zh-CN': require('./locales/zh-CN.json')
}
const i18n = new VueI18n({
locale: 'en', // 默认语言
fallbackLocale: 'en', // 回退语言
messages
})
export default i18n
在组件中使用
模板中使用 $t 方法:
<template>
<div>
<h1>{{ $t('welcome') }}</h1>
<button>{{ $t('button.submit') }}</button>
</div>
</template>
脚本中切换语言:
methods: {
changeLanguage(lang) {
this.$i18n.locale = lang
}
}
语言切换组件
实现一个语言切换下拉框:
<select v-model="$i18n.locale">
<option value="en">English</option>
<option value="zh-CN">中文</option>
</select>
持久化存储
为保持用户选择的语言,可使用 localStorage:
created() {
const savedLocale = localStorage.getItem('locale')
if (savedLocale) {
this.$i18n.locale = savedLocale
}
},
watch: {
'$i18n.locale'(newVal) {
localStorage.setItem('locale', newVal)
}
}
动态导入优化
对于大型项目,建议按需加载语言包:
async changeLanguage(lang) {
const messages = await import(`@/locales/${lang}.json`)
this.$i18n.setLocaleMessage(lang, messages.default)
this.$i18n.locale = lang
}
日期时间本地化
处理日期时间格式差异:
import { DateTime } from 'luxon'
const dateFormats = {
en: {
short: {
year: 'numeric', month: 'short', day: 'numeric'
}
},
'zh-CN': {
short: {
year: 'numeric', month: 'short', day: 'numeric'
}
}
}
const i18n = new VueI18n({
dateTimeFormats: dateFormats
})
模板中使用:
<span>{{ $d(new Date(), 'short') }}</span>






