import { AsyncDataExecuteOptions, _AsyncData } from 'nuxt/dist/app/composables/asyncData' import { Ref } from 'vue' import { useUserStore } from '~~/stores/user' interface MyUseFetchRes { data: Ref> | null refresh?: (opts?: AsyncDataExecuteOptions | undefined) => Promise | Promise<() => void> error: Ref } const useMyCustomFetch = (url: string, options?: any): Promise> => { return new Promise>( (resolve: (params: MyUseFetchRes) => any, reject: (params: MyUseFetchRes) => any) => { const { apiPrefix } = useRuntimeConfig() const _url = apiPrefix + url let _options = options const { token, clearToken } = useUserStore() if (_options) { _options.headers = { Authorization: `Bearer ${token}` } } else { _options = { headers: { Authorization: `Bearer ${token}` } } } // 请求拦截器T useFetch(_url, { ..._options }) .then(({ data, error, refresh }: _AsyncData) => { if (error.value) { if (data.value && data.value.code === 401) { // clearToken() } else { process.client ? ElMessage.error(error.value.message) : '' } reject({ data: null, refresh: refresh, error: ref(error) }) } if (data.value.code !== 200) { ElMessage.error(data.value.msg) reject({ data: data as unknown as Ref>, refresh: refresh, error: ref(error) }) } resolve({ data: data as unknown as Ref>, refresh: refresh, error: ref(error) }) }) .catch((err: any) => { reject({ data: null, error: ref(err) }) }) } ) } // 自动导出 export const useHttp = { get: (url: string, params?: any) => { return useMyCustomFetch(url, { method: 'get', params: params }) }, post: (url: string, params?: any) => { return useMyCustomFetch(url, { method: 'post', body: params }) }, put: (url: string, params?: any) => { return useMyCustomFetch(url, { method: 'put', body: params }) }, delete: (url: string, params?: any) => { return useMyCustomFetch(url, { method: 'get', body: params }) } }