Files
thinkyu/教育訓練系統/Web/Docs/ApiMixin_使用指南.md
T
sryang 577060bc78 chore: 首次簽入 Thinkyu ASP.NET 專案
- 加入 Visual Studio / ASP.NET .gitignore
- 排除建置輸出、IDE 設定、NuGet packages、大型 MSI 安裝檔
2026-09-10 09:42:37 +08:00

184 lines
5.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# ApiMixin 使用指南
## 概述
`ApiMixin` 是一个 Vue mixin,用于统一管理和简化应用中的 API 调用。它提供了两个主要方法:
- `callApi()` - 基础的 API 调用方法
- `callApiWithErrorMsg()` - 带自动错误处理的 API 调用方法
## 安装步骤
### 1. 引入 ApiMixin
在您的 HTML 页面中添加脚本引用(在 Vue 和其他依赖之后):
```html
<script src="Scripts/ApiMixin.js"></script>
```
### 2. 在 Vue 组件中使用
在您的 Vue 组件中,在 mixins 数组中添加 `ApiMixin`
```javascript
receiptEditApp = new Vue({
el: '#receiptEditApp',
mixins: [DateMixin, ToastMixin, ApiMixin], // 添加 ApiMixin
data: { ... },
// 其他选项
});
```
## API 方法
### callApi(endpoint, functionName, data)
**用途**: 调用 API 并返回原始结果
**参数**:
- `endpoint` (string): API 端点名称(.asmx 文件名)
- 示例: `'領據處理'`, `'付款設定'`
- `functionName` (string): 方法名称
- 示例: `'Save'`, `'GetOne'`, `'SearchRecipient'`
- `data` (object, 可选): 要传送的数据对象,默认为 `{}`
**返回值**: Promiseresolve 时返回 API 响应对象,reject 时返回错误对象
**示例**:
```javascript
// 基础使用
try {
const result = await this.callApi('領據處理', 'GetOne', { no: '001' });
console.log(result.Data);
} catch (error) {
console.error('API 调用失败:', error);
}
// 不等待结果
this.callApi('領據處理', 'Save', data)
.then(result => {
this.ShowSuccess(result.Message);
})
.catch(error => {
this.ShowError(error.message);
});
```
### callApiWithErrorMsg(endpoint, functionName, data, errorPrefix)
**用途**: 调用 API 并自动显示错误消息
**参数**:
- `endpoint` (string): API 端点名称
- `functionName` (string): 方法名称
- `data` (object, 可选): 要传送的数据对象
- `errorPrefix` (string, 可选): 错误消息前缀,默认为 `'操作'`
**返回值**: Promisereject 时自动调用 `this.ShowError()`
**示例**:
```javascript
// 使用自动错误处理
try {
const result = await this.callApiWithErrorMsg('領據處理', 'Save', data, '儲存');
this.ShowSuccess(result.Message);
} catch (error) {
// 错误已自动显示
console.error('操作失败:', error);
}
```
## 完整示例
### 原始代码(冗长)
```javascript
loadData(no) {
this.loading = true;
axios({
method: 'post',
url: `${API_BASE}/GetOne`,
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
data: JSON.stringify({ no })
})
.then(response => {
const result = response.data.d || response.data;
if (result.Success) {
this.mainData = result.Data.main;
this.laborData = result.Data.labor;
this.travelData = result.Data.travel;
this.backupData();
} else {
this.ShowError('載入失敗: ' + result.Message);
}
})
.catch(error => {
console.error('LoadData error:', error);
this.ShowError('載入發生錯誤: ' + (error.message || '請檢查網路連線'));
})
.finally(() => {
this.loading = false;
});
}
```
### 使用 ApiMixin 的简化代码
```javascript
async loadData(no) {
this.loading = true;
try {
const result = await this.callApiWithErrorMsg('領據處理', 'GetOne', { no }, '載入');
this.mainData = result.Data.main;
this.laborData = result.Data.labor;
this.travelData = result.Data.travel;
this.backupData();
} catch (error) {
console.error('LoadData error:', error);
} finally {
this.loading = false;
}
}
```
## 重构建议
使用 ApiMixin 后,您可以将 `領據處理.js` 中的多个方法简化:
1. **save()** - 减少 ~15 行代码
2. **loadDropdownList()** - 减少 ~10 行代码
3. **searchRecipient()** - 减少 ~10 行代码
4. **searchPlan()** - 减少 ~10 行代码
5. **searchOriginStation()** - 减少 ~10 行代码
6. **searchDestStation()** - 减少 ~10 行代码
7. **calculateTax()** - 减少 ~5 行代码
8. **calculateFare()** - 减少 ~5 行代码
**总计**: 可减少 ~65+ 行代码,提高代码可读性和可维护性
## 错误处理
ApiMixin 会自动处理以下情况:
- ✅ API 响应格式 (`data.d``data`)
- ✅ Success 字段检查
- ✅ 错误消息提取
- ✅ 网络错误捕获
- ✅ 自动显示错误(使用 `callApiWithErrorMsg`
## 注意事项
1. **ToastMixin 依赖**: `callApiWithErrorMsg` 需要 `this.ShowError()` 方法,确保您的 Vue 组件已混入 `ToastMixin`
2. **API_BASE 变量**: 确保 `API_BASE` 全局变量已定义
3. **异步/等待**: 建议在 async/await 的 try-catch 块中使用,更易读
4. **错误消息格式**: 错误消息会自动格式化为 `"{errorPrefix}失敗: {具体错误信息}"`
## 性能优化
由于所有 API 调用都走同一个方法,未来可以在 `callApi` 中添加:
- ✅ API 请求/响应日志
- ✅ 请求超时管理
- ✅ 重试机制
- ✅ 请求缓存
- ✅ 性能监测
无需修改调用代码!