Vue 之 axios封装及使用-CSDN博客

74 阅读1分钟

1,安装axios

npm install axios --save

2,建立src>axios>request.js

import axios from 'axios';
import {showLoading, hideLoading} from './loading'
import { Message } from 'element-ui';
import store from "../store";

axios.defaults.timeout = 5000;
axios.defaults.baseURL =process.env.API_ROOT;

//http request 请求拦截器
axios.interceptors.request.use(
  config => {
    // const token = getCookie('名称');注意使用的时候需要引入cookie方法,推荐js-cookie
    config.data = JSON.stringify(config.data);
    config.headers = {
      'Content-Type':'application/json'
    }
    // if(token){
    //   config.params = {'token':token}
    // }
    if (store.state.showLoading) {
      //根据标记显示loading,防止有些请求不需要loading
      showLoading();
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);


//http response 响应拦截器
axios.interceptors.response.use(
  response => {
    hideLoading();
    if(response.data.errCode ==2){
      router.push({
        path:"/login",
        querry:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
      })
    }
    return response;
  },
  error => {
    return Promise.reject(error)
  }
)


/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function get(url,params={}){
  return new Promise((resolve,reject) => {
    axios.get(url,{
      params:params
    })
      .then(response => {
        resolve(response.data);
      })
      .catch(err => {
        reject(err)
      })
  })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.post(url,data)
      .then(response => {
        resolve(response.data);
      },err => {
        reject(err)
      })
  })
}

/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.patch(url,data)
      .then(response => {
        resolve(response.data);
      },err => {
        reject(err)
      })
  })
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.put(url,data)
      .then(response => {
        resolve(response.data);
      },err => {
        reject(err)
      })
  })
}

3,同级新增loading.js

import { Loading } from 'element-ui';

let loadingCount = 0;
let loading;

const startLoading = () => {
  loading = Loading.service({
    lock: true,
    text: '请稍后……',
    background: 'rgba(0, 0, 0, 0.7)'
  });
};

const endLoading = () => {
  loading.close();
};

export const showLoading = () => {
  if (loadingCount === 0) {
    startLoading();
  }
  loadingCount += 1;
};

export const hideLoading = () => {
  if (loadingCount <= 0) {
    return;
  }
  loadingCount -= 1;
  if (loadingCount === 0) {
    endLoading();
  }
};

4,main.js引入

import axios from 'axios'
import {post,get,patch,put} from './axios/request'

5,组件中使用

 toLogin() {
         this.$post('/test1/login',{
           username:this.username,
           password: this.password
         }).then(res => {
             if (res.code===200){
               this.$message.success(res.message)
             }
           })
      }