调用接口公共组件
暴露出useRequest方法,return出三个值
- loading 加载中
- response 返回值
- 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());