axios typescript项目中,根据公司的接口定义标准的类型

request.ts的响应拦截器中返回的是response.data(这个是根据公司接口来定的,使用的时候直接response.data就可以获取导致值,如果直接return response则使用的时候需要使用 response.data.data)

axios.d.ts

import 'axios'

declare module 'axios' {
    
    

    // 所有的返回值
    interface AxiosDataResult<T>{
    
    
        code: number;
        msg: string;
        data:T
    }

    type AxiosPromiseData<T = any> = Promise<AxiosDataResult<T>>;

}

login.ts (api接口)

import request from '@/utils/request'
import type {
    
    AxiosPromiseData} from 'axios'

// 登录
interface Data{
    
    
  account: string; 
  password: string
}

//这里我的data直接就是token字符串
export function api_login(data:Data):AxiosPromiseData<string> {
    
    
  return request({
    
    
    url: '/login',
    method: 'post',
    data
  })
}

login.vue文件中使用

  api_login(form.value)
    .then(async (res) => {
    
    
      saveToken(res.data)
      await getUserInfo()

      loading.value = false
      setTimeout(() => {
    
    
        router.push('/work/index')
      }, 200)
    })
    .catch(() => {
    
    
      loading.value = false
    })

猜你喜欢

转载自blog.csdn.net/weixin_35958891/article/details/130804469