request.ts 1.5 KB
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)
}