Files
template-MP/hooks/useApi.js
2025-11-05 16:20:06 +08:00

157 lines
3.6 KiB
JavaScript
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.

import { ref, reactive } from 'vue'
import { http } from '@/api/index.js'
import tool from '@/common/utils/tool.js'
/**
* GET请求Hook
* @param {string} url 请求URL
* @param {Object} options 配置选项
* @returns {Object} 请求相关状态和方法
*/
export function useGet(url, options = {}) {
const {
manual = false, // 是否手动触发
params = {}, // 请求参数
cache = false, // 是否使用缓存
loadingDelay = 0, // loading延迟时间
onSuccess = () => {}, // 成功回调
onError = () => {}, // 失败回调
} = options
// 状态
const data = ref(null)
const loading = ref(false)
const error = ref(null)
// loading延迟定时器
let loadingTimer = null
/**
* 执行GET请求
* @param {Object} requestParams 请求参数
*/
async function run(requestParams = {}) {
// 清除之前的loading延迟定时器
if (loadingTimer) {
clearTimeout(loadingTimer)
loadingTimer = null
}
// 如果有loading延迟先启动定时器
if (loadingDelay > 0) {
loadingTimer = setTimeout(() => {
loading.value = true
}, loadingDelay)
} else {
loading.value = true
}
try {
const response = await http.get(url, {
params: { ...params, ...requestParams },
cache,
})
// 清除loading延迟定时器
if (loadingTimer) {
clearTimeout(loadingTimer)
loadingTimer = null
}
data.value = response.data
error.value = null
onSuccess(response.data)
return response.data
} catch (err) {
// 清除loading延迟定时器
if (loadingTimer) {
clearTimeout(loadingTimer)
loadingTimer = null
}
error.value = err
data.value = null
console.error(`GET请求失败: ${url}`, err)
onError(err)
throw err
} finally {
loading.value = false
}
}
/**
* 取消请求
*/
function cancel() {
if (loadingTimer) {
clearTimeout(loadingTimer)
loadingTimer = null
}
loading.value = false
}
// 如果不是手动触发,立即执行
if (!manual) {
Promise.resolve().then(() => {
run(params)
})
}
return {
data,
loading,
error,
run,
cancel,
}
}
/**
* POST请求Hook
* @param {string} url 请求URL
* @returns {Object} 请求相关状态和方法
*/
export function usePost(url) {
/**
* 执行POST请求
* @param {Object} data 请求数据
* @param {Object} options 配置选项
*/
async function run(data, options = {}) {
const { loadingDelay = 0, onSuccess = () => {}, onError = () => {} } = options
let loadingTimer = null
// 如果有loading延迟先启动定时器
if (loadingDelay > 0) {
loadingTimer = setTimeout(() => {
tool.loading()
}, loadingDelay)
} else {
tool.loading()
}
try {
const response = await http.post(url, data)
// 清除loading延迟定时器
if (loadingTimer) {
clearTimeout(loadingTimer)
loadingTimer = null
}
tool.hideLoading()
onSuccess(response.data)
return response.data
} catch (err) {
// 清除loading延迟定时器
if (loadingTimer) {
clearTimeout(loadingTimer)
loadingTimer = null
}
tool.hideLoading()
console.error(`POST请求失败: ${url}`, err)
onError(err)
throw err
}
}
return {
run,
}
}