通用请求状态hook函数useRequestStatus

180 阅读1分钟
// useStatus.ts 文件
import { ref, type UnwrapRef } from 'vue'

export function useStatus<T = number>(initStatus?: T) {
  const status = ref<T | undefined>(initStatus)
  const setStatus = (val: UnwrapRef<T>) => (status.value = val)

  return {
    status,
    setStatus
  }
}
// useLoading.ts 文件
import { ref, type UnwrapRef } from 'vue'

export function useLoading<T = boolean>(initValue?: T) {
  const loading = ref<T | undefined>(initValue)
  const setLoading = (val: UnwrapRef<T>) => (loading.value = val)

  return {
    loading,
    setLoading
  }
}
// useRequestStatus.ts 文件
import { useLoading } from './useLoading'
import { useStatus } from './useStatus'

export function useRequestStatus(loadingInitValue?: boolean, successInitValue = false) {
  const { loading, setLoading } = useLoading(loadingInitValue)
  const { status: success, setStatus: setSuccess } = useStatus<boolean>(successInitValue)

  const updateRequestStatusByPromise = (p: Promise<any>) => {
    setLoading(true)
    p.then(() => setSuccess(true)).finally(() => setLoading(false))
    return p
  }

  const resetRequestStatus = async () => {
    loading.value = undefined
    setSuccess(false)
  }

  return {
    loading,
    setLoading,
    success,
    setSuccess,
    updateRequestStatusByPromise,
    resetRequestStatus
  }
}