@vue/composition-api自定义hook

2022-04-24  本文已影响0人  小灰灰_a

react 中可以使用自定义的hook来提起一些公共方法或者对axios等进行二次封装,保障单一性,现在我们使用 composition-api 也可以实现对应的封装;

下面让我们对 axios 封装的 restApi 进行二次封装

import { ref, computed } from "@vue/composition-api"
import httpApi from "@/utils/restapi" // 为axios的封装
import { Message } from "element-ui"

export const useRequestHook = api => {
  const result = ref(null)
  const loadingState = ref(false)
  const loading = computed(() => loadingState.value)
  const res = computed(() => result.value)

  const baseUrl = ""

  const request = data => {
    const suffixPath = data?.suffixPath
    data?.suffixPath && delete data.suffixPath
    const obj = { ...api, [api.method !== "get" ? "data" : "params"]: data }
    state.value = true
    return new Promise((resolve, reject) => {
      const options = {
        method: obj.method,
        url: `${baseUrl}${obj.url}${suffixPath ? "/" : ""}${
          suffixPath ? suffixPath : ""
        }`,
        data: obj.data,
        params: obj.params,
        success: sdata => {
          resolve(sdata)
        },
        error: err => {
          Message({
              message: `${err.message}`,
              type: "error"
            })
            reject(err)
        }
      }
      httpApi.request(options)
    })
  }
  const http = async data => {
    try {
      try {
        const res = await request(data)
        result.value = res
      } catch (err) {
        console.log('====================================')
        console.log(err)
        console.log('====================================')
      }
    } finally {
      loadingState.value = false
    }
  }
  /**
    * 返回数组返回,使用时候是根据角标确定内容,解决多次使用重命名的问题
    * 也可以使用 对象 解构返回,多次使用对 参数 起别名即可
    * const exportObj = {res, loading, http}
    * return {...exportObj}
    */
  return [res, loading, http]
}

上一篇下一篇

猜你喜欢

热点阅读