# i18n 最佳实践示例
URL: /%E6%96%87%E6%A1%A3/04.%E5%BC%80%E5%8F%91%E6%96%87%E6%A1%A3/01.%20%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91/01.%20%E5%9F%BA%E7%A1%80%E8%A7%84%E8%8C%83/15.%20i18n%E5%9B%BD%E9%99%85%E5%8C%96/02.%20i18n%E6%9C%80%E4%BD%B3%E5%AE%9E%E8%B7%B5%E7%A4%BA%E4%BE%8B


# i18n 最佳实践示例

本文档提供了在实际开发中使用 i18n 的最佳实践和常见场景示例。

## 📋 目录

- [基础用法](#基础用法)
- [常见场景示例](#常见场景示例)
- [视图页面示例](#视图页面示例)
- [迁移指南](#迁移指南)

## 基础用法

### 在组件中导入 useI18n

```vue
<script setup lang="ts">
import { useI18n } from '@/hooks/web/useI18n';

const { t } = useI18n();
</script>
```

## 常见场景示例

### 1. 按钮文本

**❌ 之前（硬编码）：**
```vue
<template>
  <a-button type="primary">保存</a-button>
  <a-button @click="handleDelete">删除</a-button>
  <a-button @click="handleEdit">编辑</a-button>
  <a-button @click="handleAdd">新增</a-button>
</template>
```

**✅ 现在（使用 i18n）：**
```vue
<template>
  <a-button type="primary">{{ t('common.saveText') }}</a-button>
  <a-button @click="handleDelete">{{ t('common.delText') }}</a-button>
  <a-button @click="handleEdit">{{ t('common.editText') }}</a-button>
  <a-button @click="handleAdd">{{ t('common.addText') }}</a-button>
</template>

<script setup lang="ts">
import { useI18n } from '@/hooks/web/useI18n';

const { t } = useI18n();
</script>
```

### 2. 表单标签

**❌ 之前：**
```vue
<template>
  <a-form :model="form">
    <a-form-item label="名称">
      <a-input v-model:value="form.name" />
    </a-form-item>
    <a-form-item label="类型">
      <a-select v-model:value="form.type" />
    </a-form-item>
    <a-form-item label="状态">
      <a-radio-group v-model:value="form.status" />
    </a-form-item>
  </a-form>
</template>
```

**✅ 现在：**
```vue
<template>
  <a-form :model="form">
    <a-form-item :label="t('common.nameLabel')">
      <a-input v-model:value="form.name" :placeholder="t('common.inputText') + t('common.nameLabel')" />
    </a-form-item>
    <a-form-item :label="t('common.typeLabel')">
      <a-select v-model:value="form.type" :placeholder="t('common.chooseText') + t('common.typeLabel')" />
    </a-form-item>
    <a-form-item :label="t('common.statusLabel')">
      <a-radio-group v-model:value="form.status" />
    </a-form-item>
  </a-form>
</template>

<script setup lang="ts">
import { useI18n } from '@/hooks/web/useI18n';

const { t } = useI18n();
</script>
```

### 3. 表格操作列

**❌ 之前：**
```vue
<template>
  <BasicTable @register="registerTable">
    <template #action="{ record }">
      <TableAction
        :actions="[
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
          },
          {
            label: '删除',
            popConfirm: {
              title: '是否确认删除',
              confirm: handleDelete.bind(null, record),
            },
          },
        ]"
      />
    </template>
  </BasicTable>
</template>
```

**✅ 现在：**
```vue
<template>
  <BasicTable @register="registerTable">
    <template #action="{ record }">
      <TableAction
        :actions="[
          {
            label: t('common.editText'),
            onClick: handleEdit.bind(null, record),
          },
          {
            label: t('common.delText'),
            popConfirm: {
              title: t('common.confirmDeleteMessage'),
              confirm: handleDelete.bind(null, record),
            },
          },
        ]"
      />
    </template>
  </BasicTable>
</template>

<script setup lang="ts">
import { useI18n } from '@/hooks/web/useI18n';

const { t } = useI18n();
</script>
```

### 4. 模态框/抽屉

**❌ 之前：**
```vue
<template>
  <BasicModal title="新增用户" @register="registerModal">
    <a-form :model="form">
      <a-form-item label="用户名">
        <a-input v-model:value="form.username" />
      </a-form-item>
    </a-form>
  </BasicModal>
</template>
```

**✅ 现在：**
```vue
<template>
  <BasicModal :title="t('common.addText') + '用户'" @register="registerModal">
    <a-form :model="form">
      <a-form-item :label="t('common.nameLabel')">
        <a-input v-model:value="form.username" />
      </a-form-item>
    </a-form>
  </BasicModal>
</template>

<script setup lang="ts">
import { useI18n } from '@/hooks/web/useI18n';

const { t } = useI18n();
</script>
```

### 5. 消息提示

**❌ 之前：**
```typescript
async function handleSave() {
  try {
    await saveApi(data);
    message.success('保存成功');
  } catch (error) {
    message.error('保存失败');
  }
}
```

**✅ 现在：**
```typescript
import { useI18n } from '@/hooks/web/useI18n';
import { useMessage } from '@/hooks/web/useMessage';

const { t } = useI18n();
const { createMessage } = useMessage();

async function handleSave() {
  try {
    await saveApi(data);
    createMessage.success(t('common.saveSuccess'));
  } catch (error) {
    createMessage.error(t('common.saveFailed'));
  }
}
```

### 6. 确认对话框

**❌ 之前：**
```typescript
function handleDelete(id: string) {
  createConfirm({
    iconType: 'warning',
    title: '警告',
    content: '是否确认删除此记录？',
    onOk: async () => {
      await deleteApi(id);
      message.success('删除成功');
    },
  });
}
```

**✅ 现在：**
```typescript
import { useI18n } from '@/hooks/web/useI18n';
import { useMessage } from '@/hooks/web/useMessage';

const { t } = useI18n();
const { createConfirm, createMessage } = useMessage();

function handleDelete(id: string) {
  createConfirm({
    iconType: 'warning',
    title: t('sys.api.errorTip'),
    content: t('common.confirmDeleteMessage'),
    onOk: async () => {
      await deleteApi(id);
      createMessage.success(t('common.deleteSuccess'));
    },
  });
}
```

## 视图页面示例

### 完整的列表页面示例

```vue
<template>
  <div>
    <div class="bg-white p-4 mb-4">
      <a-form layout="inline">
        <a-form-item :label="t('common.nameLabel')">
          <a-input
            v-model:value="queryInfo.name"
            :placeholder="t('common.inputText') + t('common.nameLabel')"
            @pressEnter="handleQuery"
          />
        </a-form-item>
        <a-form-item :label="t('common.statusLabel')">
          <a-select
            v-model:value="queryInfo.status"
            :placeholder="t('common.chooseText') + t('common.statusLabel')"
            allowClear
            style="width: 150px"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleQuery">
            {{ t('common.queryText') }}
          </a-button>
          <a-button class="ml-2" @click="handleReset">
            {{ t('common.resetText') }}
          </a-button>
        </a-form-item>
      </a-form>
    </div>

    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleAdd">
          {{ t('common.addText') }}
        </a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: t('common.editText'),
              onClick: handleEdit.bind(null, record),
            },
            {
              label: t('common.delText'),
              popConfirm: {
                title: t('common.confirmDeleteMessage'),
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>

    <UserModal @register="registerModal" @success="reload" />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { BasicTable, useTable, TableAction } from '@/components/Table';
import { useI18n } from '@/hooks/web/useI18n';
import { useMessage } from '@/hooks/web/useMessage';
import UserModal from './UserModal.vue';

const { t } = useI18n();
const { createMessage } = useMessage();

const queryInfo = ref({
  name: '',
  status: undefined,
});

const [registerTable, { reload }] = useTable({
  api: getUserList,
  columns: [
    {
      title: t('common.nameLabel'),
      dataIndex: 'name',
    },
    {
      title: t('common.statusLabel'),
      dataIndex: 'status',
    },
    {
      title: t('common.createTimeLabel'),
      dataIndex: 'createTime',
    },
  ],
});

function handleQuery() {
  reload();
}

function handleReset() {
  queryInfo.value = {
    name: '',
    status: undefined,
  };
  reload();
}

function handleAdd() {
  openModal(true, {
    isUpdate: false,
  });
}

function handleEdit(record) {
  openModal(true, {
    record,
    isUpdate: true,
  });
}

async function handleDelete(record) {
  try {
    await deleteUser(record.id);
    createMessage.success(t('common.deleteSuccess'));
    reload();
  } catch (error) {
    createMessage.error(t('common.deleteFailed'));
  }
}
</script>
```

## 迁移指南

### 步骤 1: 识别需要国际化的文本

找出组件中的硬编码中文字符串，特别是：
- 按钮文本
- 表单标签
- 提示信息
- 模态框标题

### 步骤 2: 检查是否已有翻译 key

在 `src/locales/lang/zh-CN/common.ts` 中查找是否已有对应的翻译 key。

### 步骤 3: 如果没有，添加新的翻译 key

**中文翻译文件（src/locales/lang/zh-CN/common.ts）：**
```typescript
export default {
  // ...existing code
  myFeature: {
    title: '我的功能',
    description: '功能描述',
  },
};
```

**英文翻译文件（src/locales/lang/en/common.ts）：**
```typescript
export default {
  // ...existing code
  myFeature: {
    title: 'My Feature',
    description: 'Feature description',
  },
};
```

### 步骤 4: 在组件中使用

```vue
<script setup lang="ts">
import { useI18n } from '@/hooks/web/useI18n';

const { t } = useI18n();
</script>

<template>
  <div>{{ t('common.myFeature.title') }}</div>
</template>
```

## 常用翻译 key 参考

### 按钮相关
- `common.addText` - 新增
- `common.editText` - 编辑
- `common.delText` - 删除
- `common.saveText` - 保存
- `common.cancelText` - 取消
- `common.queryText` - 查询
- `common.resetText` - 重置
- `common.submitText` - 提交
- `common.okText` - 确认
- `common.backText` - 返回

### 表单相关
- `common.nameLabel` - 名称
- `common.typeLabel` - 类型
- `common.statusLabel` - 状态
- `common.timeLabel` - 时间
- `common.descLabel` - 描述
- `common.contentLabel` - 内容
- `common.remarkLabel` - 备注
- `common.inputText` - 请输入
- `common.chooseText` - 请选择

### 消息提示
- `common.operationSuccess` - 操作成功
- `common.operationFailed` - 操作失败
- `common.saveSuccess` - 保存成功
- `common.saveFailed` - 保存失败
- `common.deleteSuccess` - 删除成功
- `common.deleteFailed` - 删除失败
- `common.confirmDelete` - 确认删除
- `common.confirmDeleteMessage` - 是否确认删除

### 其他
- `common.moreText` - 更多
- `common.operation` - 操作
- `common.totalText` - 共
- `common.itemText` - 条

## 注意事项

1. **不要过度使用**：对于一些很少改变的文本，可以保持硬编码
2. **保持一致性**：相同的功能使用相同的翻译 key
3. **参数化**：对于需要动态内容的文本，使用参数化翻译
4. **模块化**：对于特定业务模块，可以创建独立的翻译文件

## 参数化翻译示例

```typescript
// 翻译文件
export default {
  message: {
    welcome: '欢迎, {name}!',
    itemCount: '共 {count} 条数据',
  },
};

// 使用
const { t } = useI18n('message');
t('welcome', { name: '张三' })  // '欢迎, 张三!'
t('itemCount', { count: 10 })   // '共 10 条数据'
```
