Files
djangoadmin-wiki/DjangoAdmin_Flask_NaiveVue/zh/volume4/frontend/i18n.md
T
2026-09-13 23:01:19 +08:00

115 lines
2.9 KiB
Markdown

# 国际化
:::tip 说明
当前项目仅支持中文界面,NaiveUI 通过 `n-config-provider` 的 `locale` 属性配置中文语言包,所有界面文本直接硬编码在组件中。如需扩展多语言支持,可基于 vue-i18n 实现。
:::
## 当前状态
项目当前为中文单语言版本:
- NaiveUI 通过 `n-config-provider` 全局配置中文语言包:`:locale="zhCN"`
- 所有界面文本直接硬编码在组件中:`<n-button>添加岗位</n-button>`
- 后端返回的 `msg` 字段为中文:`"操作成功"`、`"岗位名称不能重复"`
```vue
<template>
<n-button type="primary">添加岗位</n-button>
</template>
```
## NaiveUI 语言配置
NaiveUI 通过 `n-config-provider` 组件配置语言:
```vue
<template>
<n-config-provider :locale="zhCN" :date-locale="dateZhCN">
<router-view />
</n-config-provider>
</template>
<script setup>
import { zhCN, dateZhCN } from 'naive-ui';
</script>
```
## 扩展方案
如需支持多语言,推荐使用 vue-i18n:
### 安装依赖
```bash
pnpm add vue-i18n
```
### 配置 i18n
```typescript
// src/i18n/index.ts
import { createI18n } from 'vue-i18n';
import zhCN from './locales/zh-CN.json';
import enUS from './locales/en-US.json';
const i18n = createI18n({
legacy: false,
locale: localStorage.getItem('lang') || 'zh-CN',
fallbackLocale: 'zh-CN',
messages: { 'zh-CN': zhCN, 'en-US': enUS },
});
export default i18n;
```
### 语言文件
```json
// src/i18n/locales/zh-CN.json
{
"common": {
"add": "新增", "edit": "编辑", "delete": "删除",
"search": "搜索", "reset": "重置", "confirm": "确定", "cancel": "取消"
},
"position": { "name": "岗位名称", "status": "状态", "sort": "排序" }
}
```
### 组件中使用
```vue
<template>
<n-button type="primary">{{ $t('common.add') }}</n-button>
</template>
<script setup>
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
</script>
```
### NaiveUI 国际化
```vue
<template>
<n-config-provider :locale="currentLocale" :date-locale="currentDateLocale">
<router-view />
</n-config-provider>
</template>
<script setup>
import { zhCN, dateZhCN, enUS, dateEnUS } from 'naive-ui';
const currentLocale = computed(() => lang === 'zh-CN' ? zhCN : enUS);
const currentDateLocale = computed(() => lang === 'zh-CN' ? dateZhCN : dateEnUS);
</script>
```
:::tip 温馨提示
国际化改造工作量较大,建议在项目初期规划。如仅需中文,当前硬编码方式即可满足需求。改造时需要同时处理前端文本和后端返回的 `msg` 字段。NaiveUI 内置中文语言包,无需额外安装。
:::
## 总结
当前项目为中文单语言版本,NaiveUI 通过 `n-config-provider` 的 `:locale="zhCN"` 配置中文。如需扩展多语言支持,可基于 vue-i18n 实现前端国际化,配合 NaiveUI 内置语言包和后端消息 code 实现全链路多语言。