关于vue3:vue3-axios安装及使用

装置

应用npm装置

$ npm install axios

封装axios

/*
 * @Author: Axios封装
 * @Date: 2020-12-08 10:39:03
 * @LastEditTime: 2021-10-22 11:34:08
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \blogs-s\src\api\index.ts
 */
import axios from 'axios';
import qs from "qs";
import store from "@/store/index";
import router from '@/router/index';
import { dataList } from '@/components/aspin/data';
import { message } from 'ant-design-vue';
import { storage } from '../storage/storage';

//数据申请字符
axios.defaults.baseURL = process.env.VUE_APP_API_URL,
  // 如果申请话费了超过 `timeout` 的工夫,申请将被中断
  axios.defaults.timeout = 5000;
// 示意跨域申请时是否须要应用凭证
axios.defaults.withCredentials = false;
// axios.defaults.headers.common['token'] =  AUTH_TOKEN
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
// 容许跨域
axios.defaults.headers.post["Access-Control-Allow-Origin-Type"] = "*";

// 申请拦截器
axios.interceptors.request.use(function (config) {
  if (
    config.method === "post" ||
    config.method === "put" ||
    config.method === "delete"
  ) {
    // qs序列化
    config.data = qs.parse(config.data);
  }
  // 若是有做鉴权token , 就给头部带上token
  if (storage.get(store.state.Roles)) {
    store.state.Roles
    config.headers.Authorization = storage.get(store.state.Roles);
  }
  return config;
}, error => {
  message.error(error.data.error.message);
  return Promise.reject(error.data.error.message);
})

// 响应拦截器
axios.interceptors.response.use(function (config) {


  dataList.show = true
  if (config.status === 200 || config.status === 204) {
    setTimeout(() => {
      dataList.show = false
    }, 400)
    return Promise.resolve(config);
  } else {
    return Promise.reject(config);
  }
},
  function (error) {

    if (error.response.status) {
      switch (error.response.status) {
        case 400:
          message.error("收回的申请有谬误,服务器没有进行新建或批改数据的操作==>" + error.response.status)
          break;

        // 401: 未登录
        // 未登录则跳转登录页面,并携带以后页面的门路
        // 在登录胜利后返回以后页面,这一步须要在登录页操作。                
        case 401: //重定向
          message.error("token:登录生效==>" + error.response.status + ":" + store.state.Roles)
          storage.remove(store.state.Roles)
          storage.get(store.state.Roles)
          router.replace({
            path: '/Login',
          });
          break;
        // 403 token过期
        // 登录过期对用户进行提醒
        // 革除本地token和清空vuex中token对象
        // 跳转登录页面                
        case 403:
          message.error("用户失去受权,然而拜访是被禁止的==>" + error.response.status)
          break;
        case 404:
          message.error("网络申请不存在==>" + error.response.status)
          break;
        case 406:
          message.error("申请的格局不可得==>" + error.response.status)
          break;
        case 410:
          message.error("申请的资源被永恒删除,且不会再失去的==>" + error.response.status)
          break;
        case 422:
          message.error("当创立一个对象时,产生一个验证谬误==>" + error.response.status)
          break;
        case 500:
          message.error("服务器产生谬误,请查看服务器==>" + error.response.status)
          break;
        case 502:
          message.error("网关谬误==>" + error.response.status)
          break;
        case 503:
          message.error("服务不可用,服务器临时过载或保护==>" + error.response.status)
          break;
        case 504:
          message.error("网关超时==>" + error.response.status)
          break;
        default:
          message.error("其余谬误谬误==>" + error.response.status)
      }
      return Promise.reject(error.response);
    } else {
      // 解决断网的状况
      // eg:申请超时或断网时,更新state的network状态
      // network状态在app.vue中管制着一个全局的断网提醒组件的显示暗藏
      // 对于断网组件中的刷新从新获取数据,会在断网组件中阐明
      store.commit('changeNetwork', false);
    }
  }
)
export default axios

main.ts:

全局应用

import axios from './utils/http/axios'
全局应用
// 全局ctx(this) 上挂载 $axios
app.config.globalProperties.$api = axios

#### 封装应用

/*
 * @Author: your name
 * @Date: 2021-05-08 11:33:56
 * @LastEditTime: 2021-10-22 10:36:05
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \blogs-s\src\api\article.js
 */
import request from '@/utils/http/axios'
import { IntArticle } from "@/api/data/interData";

export class article {

  /**
   * @description: 查问总条数
   */
  static async GetCountAsync() {
    return await request({
      url: "/api/SnArticle/GetCountAsync",
      method: 'get',
    })
  }

  /**
   * @description: 查问分类总条数
   * @param {number} id
   */
  static async ConutSort(id: number) {
    return await request({
      url: "/api/SnArticle/GetConutSortAsync?type=" + id + "&cache=true",
      method: 'get',
    })
  }
  /**
   * @description: 含糊查问
   * @param {string} name
   */
  static async GetContainsAsync(name: string) {
    return await request({
      url: "/api/SnArticle/GetContainsAsync?name=" + name + "&cache=true",
      method: 'get',
    })
  }
  /**
   * @description: 按标签含糊查问
   * @param {string} name
   */
  static async GetTypeContainsAsync(tag: string, name: string, chache: boolean) {
    return await request({
      url: "/api/SnArticle/GetTypeContainsAsync?type=" + tag + "&name=" + name + "&cache=" + chache,
      method: 'get',
    })
  }

  /**
   * @description: 主键查问
   * @param {number} id
   * @param {boolean} cache
   * @return {*}
   */
  static async GetByIdAsync(id: any, cache: boolean): Promise<any> {
    return await request({
      url: "/api/SnArticle/GetByIdAsync?id=" + id + "&cache=" + cache,
      method: 'get',
    })
  }
  /**
   * @description: 按标签条件查问
   * @param {number} id
   * @param {boolean} cache
   * @return {*}
   */
  static async GetTagtextAsync(id: number, cache: boolean): Promise<any> {
    return await request({
      url: "/api/SnArticle/GetTagAsync?labelId=" + id + "&isDesc=true&cache=" + cache,
      method: 'get',
    })
  }
  /**
   * @description: 标签分页查问
   * @param {number} page
   * @param {number} pagesize
   * @return {*}
   */
  static async GetFyTitleAsync(page: number, pagesize: number, isDesc: boolean, cache: boolean): Promise<any> {
    return await request({
      url:
        "/api/SnArticle/GetFyTitleAsync?" +
        "&pageIndex=" +
        page +
        "&pageSize=" +
        pagesize +
        "&isDesc=" + isDesc + "&cache=" + cache,
      method: 'get',
    })
  }

  /**
   * @description: 分类分页查问
   * @param {number} page
   * @param {number} pagesize
   */
  static async GetFySortTitleAsync(page: number, pagesize: number, cache: boolean): Promise<any> {
    return await request({
      url: "/api/SnArticle/GetfySortTestAsync?type=7&pageIndex=" + page + "&pageSize=" + pagesize + "&isDesc=true&cache=" + cache,
      method: 'get',
    })
  }

  /**
   * @description: 更新
   * @param {any} resultData
   * @param {string} type
   */
  static async UpdatePortionAsync(resultData: any, type: string): Promise<any> {
    return await
      request({
        // 更新
        url: "/api/SnArticle/UpdatePortionAsync?type=" + type,
        method: "put",
        data: resultData,
      })
  }

  /**
   * @description: 新增数据
   * @param {any} resultData
   */
  static async AddAsync(resultData: IntArticle) {
    return await
      request({
        url: "/api/SnArticle/AddAsync",
        method: "post",
        data: resultData,
      })
  }
  /**
   * @description: 更新数据
   * @param {IntArticle} resultData
   */
  static async UpdateAsync(resultData: IntArticle) {
    return await
      request({
        url: "/api/SnArticle/UpdateAsync",
        method: "put",
        data: resultData,
      })
  }
  /**
   * @description: 删除
   * @param {number} id
   * @return {*}
   */
  static async DeleteAsync(id: number) {
    return await
      request({
        url: "/api/SnArticle/DeleteAsync?id=" + id,
        method: "delete",
      })
  }
}

axios 并发申请

解决并发申请的助手函数

axios.all(iterable)

axios.spread(callback)

//示例:
import { article } from '@/api/index';
import { blogsList } from "./components/data";
import axios from '@/utils/http/axios'
class methods {
  static async GetFySortTitle() {
    await article.GetFySortTitleAsync(blogsList.page, blogsList.pagesize, true).then((res: any) => {
      blogsList.dataResult = res.data;
    });
  }
  static async ConutSort() {
    await article.ConutSort(7).then((result: any) => {
      blogsList.count = result.data;
    });
  }
}
async function QueryAll() {
  // axios.all([await methods.ConutSort(), await methods.GetFySortTitle()]).then(axios.spread((Fy, co: any) => {
  //   blogsList.count = co.data;
  //   blogsList.dataResult = Fy.data;
  // }))
  axios.all([await methods.ConutSort(), await methods.GetFySortTitle()])
}

export {
  methods,
  QueryAll
}

【腾讯云】云产品限时秒杀,爆款1核2G云服务器,首年50元

阿里云限时活动-2核2G-5M带宽-60G SSD-1000G月流量 ,特惠价99元/年(原价1234.2元/年,可以直接买3年),速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表评论

您的电子邮箱地址不会被公开。

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据