vue 中使用 axios 封装及使用

一, 配置BaseUrl

/**
 * {
 *   dev: '开发环境配置信息',
 *   test: '测试环境配置信息',
 *   prod: '线上环境配置信息'
 * }
 */
function conf (base = {}) {
  if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'testing') { // 生产环境下
    let env = process.env.ENV_CONFIG || 'dev'
    return base[env] || base['dev']
  }
  // 开发环境
  return base['dev']
}

// baseUrl
export const baseUrl = conf({
  dev: 'http://`````',
  test: 'http://`````',
  prod: 'http://`````'
})

二, 配置axios , 创建axios.js

import axios from 'axios'
import {baseUrl} from './env'

var axiosBaseUrl = ''
export default async (url = '', data = {}, type = 'GET', headers = {}) => {

  type = type.toLowerCase()
  switch (type) {
    case 'post':
      return axios.post(baseUrl+ url, data, headers)
        .then((res) => { 
          return res
        })
        .catch((error) => {
          return error
        })
    case 'put':
      return axios.put(baseUrl+ url, data)
        .then((res) => {
          return res
        })
        .catch((error) => {
          return error
        })
    default:
      return axios({
        method: type,
        baseUrl: baseUrl,
        url: url,
        data: data,
        timeout: 10000,
        headers: {
          'X-Requested-With': 'XMLHttpRequest',
          // 'X-Frame-Options': 'DENY', // 告诉浏览器不要(DENY)把这个网页放在iFrame内,通常的目的就是要帮助用户对抗点击劫持。
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
      }).then((res) => {
        return res
      }).catch((error) => {
        return error
      })
  }
}

三, 配置拦截器 interceptors.js

/**
 *
 * @title 拦截器
 * @Description 与后台接口对接前后做处理用的
 * @Author 申
 * @Date 2020-03-19
 * @Version 1.0
 */
import Vue from 'vue'
import {
    MessageBox
} from 'element-ui'
import store from '@/store'
import axios from 'axios'
import QS from 'qs'
import {
    getStore
} from '@/utils/index'
var _bus = new Vue()
// 添加请求拦截器
let num = 0;
axios.interceptors.request.use(function (config) {
    //url == queryPayState 不显示loading
    if (config.url.indexOf('queryPayState') == -1) {
        num++
        // 打开加载框
        _bus.$emit('showloading')
    }

    config.data = QS.stringify(config.data)
  
  
  //header 中添加token let store = JSON.parse(getStore('store')) if (store && store.token) config.headers.token = store.token if (config.type === 'formData' || config.method !== 'post') { return config } return config }, function (error) { return Promise.reject(error) }) // 添加响应拦截器 axios.interceptors.response.use(function (response) { if (response.config.url.indexOf('queryPayState') == -1) { num-- if (num <= 0) { //关闭加载框 _bus.$emit('closeloading') } else { _bus.$emit('showloading') } } if (response.data.msgCode) { // 处理返回异常信息 if (response.data.msgCode === '10003') { store.commit('SET_TOKEN', '') if (num <= 0) { MessageBox.alert('登录信息超时, 请重新登录!', '登录超时', { confirmButtonText: '打开登录页面', callback: action => { // window.location.href = "/#/?islogin=false" // window.history.back(); store.commit('SET_isloginModel', true) } }) } } if (response.data.msgCode !== '0') { // MessageBox.alert(response.data.msg, '提示') } } return response.data }, function (error) { // 关闭loading _bus.$emit('showloading') return Promise.reject(error) }) export var bus = _bus

  四, 使用api.js

import http from './axios'
/**
 *  登录
 */
export const login = data => http('/weblogin/accountLogin.do', data, 'post')

//获取赛历
export const queryMatchCalendar = () => http('/matchInfo/queryMatchCalendar.do', {}, 'post')

  五,在页面中使用 index.vue

<template>
    <div>
        <Header></Header>
        <div class="container">
        </div>
        <Footer></Footer>
    </div>
</template>

<script>
    import { fileDownload } from '@/api/api'
    export default {
        data() {
            return {
                fileList: []
            }
        },
        mounted() {
            this.fileDownload()
        },
        methods: {
            async fileDownload() {
                const res = await fileDownload()
                if(res.msgCode === '0') {
                    this.fileList = res.data.dataList
                }else{
                    // 异常处理
                }
            }
        }
    }
</script>