request.ts
1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { ElLoading } from 'element-plus'
let loadingInstance: ReturnType<typeof ElLoading.service> | null = null
let requestCount = 0
const showLoading = () => {
if (requestCount === 0) {
loadingInstance = ElLoading.service({
lock: true,
text: '加载中...',
background: 'rgba(255, 255, 255, 0.7)',
})
}
requestCount++
}
const hideLoading = () => {
requestCount--
if (requestCount <= 0) {
requestCount = 0
if (loadingInstance) {
loadingInstance.close()
loadingInstance = null
}
}
}
const useMyfetch = async (url: any, options?: any, headers?: any) => {
try {
showLoading()
const config = useRuntimeConfig()
const reqUrl = config.public.apiUrl + url
const customHeaders = {
Authorization: useCookie('accessToken').value,
...headers
}
const { data, pending } = await useFetch(reqUrl, {
...options,
watch: false,
headers: customHeaders
})
const result = data.value as any
return result
} catch (err) {
return Promise.reject(err)
} finally {
hideLoading()
}
}
export const useGet = (url: string, params?: any, headers?: any) => {
return useMyfetch(url, { method: 'get', params }, headers)
}
export const usePost = (url: string, params?: any, headers?: any) => {
return useMyfetch(url, { method: 'post', body: params }, headers)
}
export const usePut = (url: string, params?: any, headers?: any) => {
return useMyfetch(url, { method: 'put', body: params }, headers)
}