55 lines
2.2 KiB
JavaScript
55 lines
2.2 KiB
JavaScript
/**
|
|
* API Mixin - 统一的 API 调用管理
|
|
* 用法: 在 Vue 组件中引入此 mixin,然后使用 this.callApi(endpoint, functionName, data)
|
|
*/
|
|
const ApiMixin = {
|
|
methods: {
|
|
/**
|
|
* 调用 API 的通用方法
|
|
* @param {string} endpoint - API 端点(.asmx 文件名,不需要扩展名),如 '領據處理'
|
|
* @param {string} functionName - 方法名称,如 'Save', 'GetOne'
|
|
* @param {object} data - 要传送的数据对象
|
|
* @returns {Promise} 返回 Promise,包含 API 响应数据
|
|
*/
|
|
callApi(endpoint, functionName, data = {}) {
|
|
console.log(`callApi [${endpoint}/${functionName}]`, data);
|
|
return axios({
|
|
method: 'post',
|
|
url: `${API_BASE}/${endpoint}.asmx/${functionName}`,
|
|
headers: {
|
|
'Content-Type': 'application/json; charset=utf-8'
|
|
},
|
|
data: JSON.stringify(data)
|
|
})
|
|
.then(response => {
|
|
const result = response.data.d || response.data;
|
|
if (result.Success) {
|
|
return Promise.resolve(result);
|
|
} else {
|
|
return Promise.reject(new Error(result.Message || '操作失败'));
|
|
}
|
|
})
|
|
.catch(error => {
|
|
console.error(`API 調用失敗 [${endpoint}/${functionName}]:`, error);
|
|
return Promise.reject(error);
|
|
});
|
|
},
|
|
|
|
/**
|
|
* 调用 API 并显示错误消息的便捷方法
|
|
* @param {string} endpoint - API 端点
|
|
* @param {string} functionName - 方法名称
|
|
* @param {object} data - 数据对象
|
|
* @param {string} errorPrefix - 错误消息前缀
|
|
* @returns {Promise}
|
|
*/
|
|
callApiWithErrorMsg(endpoint, functionName, data = {}, errorPrefix = '操作') {
|
|
return this.callApi(endpoint, functionName, data)
|
|
.catch(error => {
|
|
this.ShowError(`${errorPrefix}失敗: ${error.message || '請檢查網路連線'}`);
|
|
return Promise.reject(error);
|
|
});
|
|
}
|
|
}
|
|
};
|