vue -----Vue.http 和 axios

vue.$http: vue 2.0以後不對vue-resource進行維護,無法對請求進行取消

axios:可以進行手動取消請求,複用性好

axios二次封裝使用

大概流程:

  1. 引入 vue 和 axios
  2. 定義類class Ajax{}
  3. 構造函數(constructor)裏寫初始化事件
    (1). 重寫methods方法
    (2). 請求攔截(接口地址進行處理), 響應攔截(成功失敗信息)
    4.導出axios

業務使用:
定義一個api掛載到全局vue.prototype, 然後業務 this.$api訪問

api內容:

每個模塊定義一個index.js 包含當前模塊所有的請求
import axios from ‘util/axios’
axios.post(ur;, data);

外面接口層導出各個模塊

import Vue from 'vue';
import Axios from 'axios';

class Ajax {
	constructot () {
		this.axios = Axios;
        this.token = 'CSRFPreventionToken';
        this.noAuthCode = 401;
        this.successCode = 0;

        this.initAxios();
	}

	initAxios () {
        this.axios.defaults.baseURL = '/test';
        this.axios.defaults.headers.common[this.token] = '值';
        this.axios.defaults.timeout = 60000;
        this.rewriteMethods();
        this.reqInterception();
        this.resInterception();
    }
	rewriteMethods () {
        ['get', 'head', 'jsonp'].forEach(method => {
            this.axios[method] = (url, data, options = {}) => {
                let params = [];
                if (data) {
                    for (let key in data) {
                        if (data.hasOwnProperty(key)) {
                            params.push(key + '=' + encodeURIComponent(data[key]));
                        }
                    }
                }

                if (url.indexOf('?') === -1) {
                    url += '?' + params.join('&');
                } else {
                    url += '&' + params.join('&');
                }

                if (url && typeof url === 'string') {
                    Object.assign(options, { url, method });
                }

                return this.axios(options);
            };
        });
    }
  //請求攔截器,對地址進行處理

    reqInterception () {
        this.axios.interceptors.request.use(config => {   
            config.url = this.fixURL(config.url);

            // 絕對路徑的url不要加baseURL
            if (config.url.slice(0, 1) === '/') {
                config.baseURL = '';
            }

            return config;
        });
    }

    //   響應攔截器,對成功響應數據進行處理
    
    resInterception () {
        this.axios.interceptors.response.use(
            this.successHandle.bind(this), 
            this.errorHandle.bind(this)
        );
    }

    successHandle (response) {
        const URL = response.config.url;
        const STATUS = response.status;
        let data = response.data || {};

        data.status = STATUS;

        if (!data.success) {
            // 拋出報錯信息,包括接口名,接口返回的數據
            Promise.reject({
                url: URL,
                data
            });
        }

        return data;
    }

    errorHandle ({config, response}) {
        const MSG = typeof STATUS_MAP[response.status] === 'function' ? STATUS_MAP[response.status](config.url) : STATUS_MAP[response.status];
        const ERROR = {
            success: false,
            status: response.status,
            msg: MSG || response.data
        };
        Vue.prototype.$showErr(ERROR.msg);
        return Promise.reject(ERROR);
    }

}

export default new Ajax().axios;
發佈了62 篇原創文章 · 獲贊 4 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章