Skip to content

国际化

vue3-element-admin 内置完整的国际化(i18n)支持,基于 vue-i18n 实现,支持中文、英文等多种语言切换。

介绍

国际化是现代 Web 应用的重要特性,vue3-element-admin 提供了开箱即用的国际化解决方案:

  • 🌍 多语言支持 - 默认支持中文和英文,可轻松扩展
  • 🔄 动态切换 - 运行时动态切换语言,无需刷新页面
  • 📦 按需加载 - 语言包支持懒加载,优化首屏性能
  • 🎨 Element Plus 集成 - 自动同步 Element Plus 组件语言
  • 🔧 灵活配置 - 支持菜单、路由、消息等全方位国际化

项目结构

src/lang 目录管理语言包:

bash
lang/
├── index.ts       # 国际化配置入口
├── zh-cn.ts       # 中文语言包
├── en.ts          # 英文语言包
└── package/       # 按模块拆分(可选)
    ├── common.ts
    ├── route.ts
    └── components.ts

使用方式

在模板中使用

vue
<template>
  <div>
    <h1>{{ $t('common.title') }}</h1>
    <p>{{ $t('common.welcome', { name: 'Admin' }) }}</p>
  </div>
</template>

在脚本中使用

typescript
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

console.log(t('common.title'))

语言包示例

typescript
// lang/zh-cn.ts
export default {
  common: {
    title: '后台管理系统',
    welcome: '欢迎 {name}',
    confirm: '确定',
    cancel: '取消'
  },
  menu: {
    dashboard: '首页',
    system: '系统管理',
    user: '用户管理'
  }
}

// lang/en.ts
export default {
  common: {
    title: 'Admin System',
    welcome: 'Welcome {name}',
    confirm: 'Confirm',
    cancel: 'Cancel'
  },
  menu: {
    dashboard: 'Dashboard',
    system: 'System',
    user: 'User'
  }
}

切换语言

typescript
import { useI18n } from 'vue-i18n'

const { locale } = useI18n()

// 切换为英文
locale.value = 'en'

// 切换为中文
locale.value = 'zh-cn'

Element Plus 国际化

项目已配置 Element Plus 国际化:

typescript
import { createI18n } from 'vue-i18n'
import ElementPlusZhCn from 'element-plus/dist/locale/zh-cn.mjs'
import ElementPlusEn from 'element-plus/dist/locale/en.mjs'

const i18n = createI18n({
  locale: 'zh-cn',
  messages: {
    'zh-cn': { ...zhCn, ...ElementPlusZhCn },
    'en': { ...en, ...ElementPlusEn }
  }
})

相关链接

基于 MIT 许可发布