vue封装axios


最近在学习ES6,正好项目用到vue,axios封装请求,写的不好,欢迎大神指教。

环境安装

vue官网
vue-cli的文档
axios中文文档
vue init webpack vue-axios
cd vue-axios
yarn start
yarn add axios


封装axios请求

新建http.js

import axios from 'axios';
import qs from 'qs';

//跨域请求
axios.defaults.withCredentials = true

const httpServer = (opts, data) => {
  let httpDefaultOpts = {
    method: opts.method,
    url: opts.url,
    timeout: 3000,
    data: JSON.stringify(data),
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'X-Requested-With': 'XMLHttpRequest',
    }
  }

  let promise = new Promise((resolve,reject)=>{
    axios(httpDefaultOpts).then(
        res=>{
            resolve(res)
        }
        ).catch(error=>{
            reject(error)
        })
  })

  return promise;
}
export default httpServer

有关promise参考es6-promise
测试连接http

import http from '../util/http.js'
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods:{
    test(){
      let opt={
        method:'get',
        url:'www.baidu.com'
      }
     let  data={
        userCode:"fff"
      }
      http(opt,data).then(res=>{
        console.log(res);
      }).catch(err=>{
        console.log(err);
      })
    }
  }
}

简单的请求封装已经完成,接下来继续优化

1优化get post请求
 let Public = { //公共参数
       xxxx:''
    }
  data = Object.assign(Public,data);
  let httpDefaultOpts = { //http默认配置
        method: opts.method,
        url: opts.url,
        showLoading: opts.showLoading,
        timeout: 3000,
        data: JSON.stringify(data),
        params: data,
        headers: opts.method == 'get' ? {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-Requested-With': 'XMLHttpRequest',
        } : {
            "Accept": "application/json",
            'X-Requested-With': 'XMLHttpRequest',
            "Content-Type": "application/json; charset=UTF-8"
        }
    };
    if (opts.method == 'get') {
        delete httpDefaultOpts.data;
    } else {
        delete httpDefaultOpts.params;
    }
2请求成功或错误判断

如果请求成功

function successState(res) {
    if (res.data.returnCode != "0") {
        Message({ message: res.data.errorMessage, type: "error" });
    }
}

请求错误

function errorState(error) {
    // 如果http状态码正常,则直接返回数据
    if (error && (error.status === 200 || error.status === 304 || error.status === 400)) {
        return response
            // 如果不需要除了data之外的数据,可以直接 return response.data
    } else {
        Message({
            message: '网络连接超时,请检查网络',
            type: 'error'
        });
return error;
    }
}

在promise 中调用

let promise = new Promise((resolve, reject) => {
    axios(httpDefaultOpts).then(
      res => {
        successState(res)
        resolve(res)
      }
    ).catch(error => {
      errorState(error)
      reject(error)
    })
  })
引入element-ui

yarn add element-ui
添加loading服务

function endLoading() {
    loading.close()
}
let needLoadingRequestCount = 0

export function showFullScreenLoading() {
    if (needLoadingRequestCount === 0) {
        startLoading()
    }
    needLoadingRequestCount++
}

export function tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return
    needLoadingRequestCount--
    if (needLoadingRequestCount === 0) {
        endLoading()
    }
}
axios请求添加拦截器 以及添加loading
axios.interceptors.request.use(config => {
    if (config.showLoading != false) {
        showFullScreenLoading()
    }

    return config
}, error => {
    return Promise.reject(error)
})

axios.interceptors.response.use(response => {
    tryHideFullScreenLoading()
    return response
}, error => {
    tryHideFullScreenLoading()
    return Promise.reject(error)
})

至此 大功告成,持续改进更新中
https://github.com/zdyang1991/vue-axios.git

你可能感兴趣的:(vue封装axios)