需要实现的效果是请求成功之后使用返回的数据不需要抓包看属性,直接获取对象属性开始使用。
在这里插入图片描述

开始封装

axios的请求响应拦截

// 封装请求
import axios, {AxiosInstance} from "axios";
import {message} from 'ant-design-vue'
// 请求
const http: AxiosInstance = axios.create({
    // baseURL: process.env.VUE_APP_API_URL||'',
    timeout: 6000,
});
// 请求拦截
http.interceptors.request.use(
    (config: any) => {
        //请求头设置
        const token = localStorage.getItem("token") || "";
        config.headers.Authorization = token;
        config.headers["Content-Type"] = "application/json;charset=UTF-8";
        return config;
    },
    (err: any) => {
        console.log(err);
    }
);
// 响应拦截
http.interceptors.response.use(
    (res: any) => {
        const {data} = res as apiResult<any>
        if (data.state === 200) {
            return data;
        } else {
            // 这里已经是接口异常了,不需要回调了
            message.error(data?.message)
            throw new Error(data?.message)
        }
    },
    (err: any) => {
        console.log(err);
    }
);

*注意 响应拦截的地方做了状态判断,state==200才会放行否则抛出异常

开始做接口调用

做之前先准备一个回调结果的代理type

export type apiResult<T> = {
    cause: "";
    data: T;
    message: string;
    request: null;
    state: number;
    total: null;
    variables: any;
    version: null;
};

然后就是调用的请求函数,注意这个函数是接收泛型的,泛型为成功后data的类型(是响应的data不是http的)

export const request = async <T>({method = "get", url = "", data = {}, params = {},}) =>
    await http({
        method,
        url,
        data,
        params,
    }) as unknown as apiResult<T>

开始封装具体的接口

这里有两个类型
fetch-type:约定函数调用的传参
dto-type: 约定返回data的类型,这个一般是后端的实体类,转化成type格式需要自己维护。

import {request} from "../axiosConfig";
import {userFetchType} from "./fetch-type";
import {userDtoType} from "./dto-type";

const mockUrl=`http://127.0.0.1:4523/mock/1349724/mock/user`
// 查询帮助文档列表
export const fetchUserById = (data: userFetchType) =>
    request<userDtoType>({url: mockUrl, method: "post", data});

两个类型

export type userDtoType = {
    userName: string,
    age: number
}
export type userFetchType = {
    userId: string
}

调用方法已截图,结束!

也可以不结束,接着来做个hooks管理请求的状态

import {ref} from "vue";
import {apiResult} from "../api/axiosConfig";

/**
 *
 * @param fun 异步函数
 * @param params 函数参数
 * T:回调data的泛型
 * T2:param的泛型
 */
export const useRequest = <T, T2>(fun: (data: T2) => Promise<apiResult<T>>, params: T2) => {
    const loading = ref(false)
    const data = ref<T>()
    const fetch = async () => {
        loading.value = true
        const res: apiResult<T> = await fun(params) as unknown as apiResult<T>
        data.value = res.data
        loading.value = false
    }
    fetch()
    return {loading, fetch, data}
}

具体的使用

<script setup lang="ts">
import {fetchUserById} from "../../api/fileHelp";
import {useRequest} from "../../hooks";
 

const {data, loading, fetch} = useRequest (fetchUserById, {userId: 'mock-user-id'})

</script>
<template>
  <div @click="fetch">fetch</div>
  {{ data }}
  {{ loading }}
</template>
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐