request.ts
1.4 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
import { ElLoading } from 'element-plus'
const useMyfetch = async (url: any, options?: any, headers?: any) => {
let loadingInstance
try {
loadingInstance = ElLoading.service()
const config = useRuntimeConfig() // 3.0正式版环境变量要从useRuntimeConfig里的public拿
const reqUrl = config.public.baseUrl + url // 你的接口地址
// 不设置key,始终拿到的都是第一个请求的值,参数一样则不会进行第二次请求
// 可以设置默认headers例如
const customHeaders = {
Authorization: useCookie('accessToken').value,
...headers
}
const { data, pending } = await useFetch(reqUrl, {
...options,
watch: false,
headers: customHeaders
})
const result = data.value as any
if (pending && loadingInstance) {
loadingInstance.close()
}
return result
} catch (err) {
return Promise.reject(err)
} finally {
if (loadingInstance) {
loadingInstance.close()
}
}
}
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)
}