vue axios优雅写法

81 阅读1分钟

1.新建model/axios.ts(可以加拦截器和响应器)

import  axios from  "axios";
//请求的拦截器
axios.interceptors.request.use(function (config:any) {
    // 在发送请求之前做些什么
    if(window.localStorage.getItem("token")){
        config.headers.token = window.localStorage.getItem("token")
    }
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });


// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
        if(response.data.code==403){
            window.location.href="/";
        }
    return response;
  }, function (error:any) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    if(error.response.status == 404){
        alert("接口地址错误");
    }
    return Promise.reject(error);
  });

export  default  axios;

2.新建model/api统一管理请求接口地址

let  api  = {
    userinfo:{
        login:"/api/users/login",
        menuinfo:"/api/users/getrouter",
        list:"/api/users/userlist",
        add:"/api/users/register",
        insertmany:"/api/users/insertmany"
    },
    leave:{
        add:"/api/leaves/add",
        leavelist:"/api/leaves/leavelist",
        leavealllist:"/api/leaves/leavealllist",
        update:"/api/leaves/update",
        group:"/api/leaves/group"
    }
}
export  default  api;

3.新建service/userinfo.ts管理接口

import  axios from  "../model/axios";
import  api from  "../model/api";

//可以新建interfac/usermodel分离
interface  userModel{
    _id?:string,
    username:string,
    userpwd:string,
    type?:number

}

export  const  userLogin = (data:userModel)=>{
        return   axios({
            method:"post",
            url:api.userinfo.login,
            data
        })
}

export const  userMenu  = ()=>{
    return  axios({
        method:"get",
        url:api.userinfo.menuinfo
      
    })
}

export const  userList  = ()=>{
    return  axios({
        method:"get",
        url:api.userinfo.list
      
    })
}

export  const  addUser = (data:userModel)=>axios({
        method:"post",
        url:api.userinfo.add,
        data
    })
export  const  insertMany = (data:any)=>axios({
        method:"post",
        url:api.userinfo.insertmany,
        data
       
    })

4.使用

import  {insertMany} from  "@/service/userinfo";
//一个change事件
let  change  =async (e:any)=>{
  let {data}  = await  insertMany({list});
  if(data.code==200){
    emit("addList",data.list);
  }else{
    alert(data.msg);
  }
}

5.ps

//如果新建Iservice/userService规范接口
import partyModel from '../interface/partyModel'
interface Party {   
    queryPartyA(params: any): any,  // 查询甲方
    addPartyA(data: partyModel): any,
    delPartya(id: number): any
    }
  
//在service文件下用class 类名 implement 这个接口名{
//           原代码
//}
最后export default new 类名