Vue基于axios的二次封装

主要目的:速度快,好维护,好修改,好扩展,好开发

模块分析

初始化模块——请求生成模块——请求控制模块——请求处理模块

设计思路

功能分析——板块梳理——架构基础——功能构建

直接上代码吧

import axios from 'axios'


// main.js文件
// 注入main.js    import a from './byAxios';
// axios.defaults.baseURL='';
// Vue.prototype.a=a([{name:'apione',url:''},{name:'apitwo',url:''}]);


// app.vue文件
// data部分
// apione:''
// method部分
// this.a.v(this);
// this.a.apione();
// this.a.apitwo();

export default function(arr){
    function _myaxios(){
        this.vueob=null;
        this.status=true;
    }
    _myaxios.prototype.v=function(ob){
        this.vueob=ob;
    }
    // 生成请求
    _myaxios.prototype.getAxios=function(){
        var _url=config.url;
        var _type=config.type;
        var _data=config.data;.
        var requestMode={
            get:function(){
                return axios.get(_url)
            },
            post:function(){
                return axios.post(_url,_data)
            }
        }
        return requestMode[_type];
    }
    // 发送请求
    _myaxios.prototype.sendAxios=function(config){
        var _axios=this.getAxios(config);
        var self=this;
        if(this.status||!config.isBlock){
            config.isBlock?this.status=false:"";
            _axios().then(function(res){
                self.status=true;
                config.success=='default'?self.handleAxios(config.dataname,res.data):config.success.call(self.vueob,res);
            })
        }

    }
    // 处理请求
    _myaxios.prototype.handleAxios=function(dataname,data){
        this.vueob[dataname]=data
    }
    // 初始化部分
    var object=_myaxios()
    arr.forEach(function(item,index){
        object[item.name]=function(config){
            object.sendAxios({
                url:item.url,
                type:config&&config.type||'get',
                success:config&&config.success||'default',
                data:config&&config.data||{},
                dataname:config&&config.dataname||item.name,
                isBlock:config&&config.isBlock||true   //是否并行请求
            })
        }
    });
    return object
}
发布了82 篇原创文章 · 获赞 46 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/weixin_43720095/article/details/95917520