国际化
概述
Naive Admin Max 使用 Vue I18n 11 实现国际化,内置中文(zh-CN)和英文(en-US)两种语言包。框架层(表格工具栏、HTTP 错误提示等)已接入国际化,业务页面可按需补齐。
使用方式
组件内使用
在 Vue 组件中使用 useI18n() 的 t() 函数:
vue
<script setup lang="ts">
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
</script>
<template>
<NButton>{{ t('common.search') }}</NButton>
<NButton>{{ t('common.reset') }}</NButton>
</template>非组件中使用
在工具函数、Store 等非组件代码中,直接引用 i18n 实例:
typescript
import i18n from '@/i18n'
const { t } = i18n.global
// HTTP 错误提示中使用
const errorMessage = t(`http.status.${code}`)推荐做法
- 组件内:始终使用
useI18n()的t(),支持组件级作用域 - 非组件:使用
i18n.global.t(),访问全局语言包
语言包结构
语言包文件位于 src/i18n/locales/ 目录下:
src/i18n/
├── index.ts # i18n 实例配置
└── locales/
├── zh-CN.ts # 中文语言包
└── en-US.ts # 英文语言包语言包按模块组织:
typescript
// locales/zh-CN.ts
export default {
common: {
search: '搜索',
reset: '重置',
create: '新增',
edit: '编辑',
delete: '删除',
// ...
},
http: {
status: {
401: '未授权,请重新登录',
403: '拒绝访问',
404: '请求地址不存在',
500: '服务器内部错误',
},
},
// ... 更多模块
}新增语言包步骤
如需添加新的语言(如日语),按以下步骤操作:
创建语言包文件
typescript// src/i18n/locales/ja-JP.ts export default { common: { search: '検索', reset: 'リセット', create: '新規作成', // ... }, }在 i18n 配置中注册
typescript// src/i18n/index.ts import jaJP from './locales/ja-JP' const i18n = createI18n({ locale: 'zh-CN', messages: { 'zh-CN': zhCN, 'en-US': enUS, 'ja-JP': jaJP, // 新增 }, })在偏好设置中添加语言选项
在
settingsStore的语言选项中添加新语言,让用户可以在偏好设置中切换。
Naive UI Locale 跟随
Naive UI 组件库的内置文案(如日期选择器、分页器等)会自动跟随当前语言设置:
vue
<script setup lang="ts">
import { NConfigProvider, dateZhCN, zhCN } from 'naive-ui'
import { computed } from 'vue'
import { useSettingsStore } from '@/stores/settings'
const settingsStore = useSettingsStore()
// Naive UI locale 跟随系统语言设置
const naiveLocale = computed(() => {
return settingsStore.locale === 'zh-CN' ? zhCN : null
})
const naiveDateLocale = computed(() => {
return settingsStore.locale === 'zh-CN' ? dateZhCN : null
})
</script>
<template>
<NConfigProvider :locale="naiveLocale" :date-locale="naiveDateLocale">
<App />
</NConfigProvider>
</template>注意
切换语言后,Naive UI 的组件文案(如"确定"、"取消"等)会自动更新,无需手动处理。