多语言配置
本项目使用 vue-i18n 实现国际化,支持中文(zh-CN)和英文(en)。
语言文件结构
src/i18n/
├── index.ts # i18n 初始化与 setLocale 导出
└── locales/
├── zh-CN.json # 中文翻译
└── en.json # 英文翻译切换语言
使用 setLocale() 函数切换语言:
ts
import { setLocale } from '@/i18n'
// 切换到英文
setLocale('en')
// 切换到中文
setLocale('zh-CN')setLocale() 会自动完成以下操作:
- 更新
i18n.global.locale - 持久化到
localStorage('locale') - 设置
document.documentElement.lang
初始语言推断
getInitialLocale() 按以下优先级确定初始语言:
localStorage中保存的偏好navigator.language浏览器语言设置- 默认
zh-CN
添加新语言
- 在
src/i18n/locales/下创建新的 JSON 文件(如ja.json) - 在
src/i18n/index.ts中导入并注册 - 更新
LocaleKey类型和languageLabel映射
在模板中使用
vue
<template>
<p>{{ t('home.title') }}</p>
</template>
<script setup>
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
</script>Element Plus locale 联动
App.vue 中使用 el-config-provider 动态切换 Element Plus 的 locale:
vue
<el-config-provider :locale="epLocale">
<router-view />
</el-config-provider>epLocale 是一个 computed,根据当前语言自动返回 zhCn 或 en。
