uniapp-typescript网络请求封装

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

开始封装

axios的请求响应拦截

export type apiResult<T = any> = {
  cause: '';
  data: T;
  message: string;
  request: null;
  state: number;
  total: number;
  variables: any;
  version: null;
};
const http = <T = any>(options: any) => new Promise((resolve, reject) => {
  // eslint-disable-next-line no-undef
  uni.request({
    // 官方文档说是默认携带cookie(h5环境),实际体验并非如此
    withCredentials: true,
    url: options.url,
    method: options.method || 'get',
    data: options.data || {},

    // 请求成功的回调,可以在方法做返回状态码的判断。也可以直接返回resolve  ==》success: resolve,fail:reject
    success: (res: any) => {
      const { data } = res;
        data as apiResult<T>;
        if (data.state === 200) {
          resolve(data);
        }
        // 这里已经是接口异常了,不需要回调了
        // message.error(data?.message);
        throw new Error(data?.message);
    },
    // 请求失败的回调,可以在方法。反馈用户、提示用户,也可以直接返回reject  ==》success: resolve,fail:reject
    fail: (err) => {
      reject(err);
    },
  });
});

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

开始做接口调用

调用的请求函数,注意这个函数是接收泛型的,泛型为成功后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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值