调用接口的公共组件

180 阅读1分钟

调用接口公共组件

暴露出useRequest方法,return出三个值

  1. loading 加载中
  2. response 返回值
  3. fetch 方法名
import { ref } from 'vue';
import useLoading from './loading';

export default function useRequest(api, defaultValue, isLoading = true) {
  const { loading, setLoading } = useLoading(isLoading);

  const response = ref(defaultValue);

  const fetch = () => {
    setLoading(true);
    return api()
      .then((res) => {
        response.value = res;
      })
      .finally(() => {
        setLoading(false);
      });
  };

  return { loading, response, fetch };
}

组件中使用

import useRequest from '@/hooks/request';
const { loading, response, fetch } = useRequest(() => 接口名());
const getData = async () => {
    await fetch();
  };
getData();

需要调用多个接口

 const { response: 返回值1, fetch: get接口名1 } = useRequest(() => 接口名1());
 const { response: 返回值2, fetch: get接口名2 } = useRequest(() => 接口名2());
 const { response: 返回值3, fetch: get接口名3 } = useRequest(() => 接口名3());