image555小屋

welcome my blog

Vue2中axios请求封装

By image555

发表于 2017-07-14

如何安装请移步axios,文档描述的很清楚。

其实我们用的最多的就是get、post请求。


utils.js文件
export const Ajax= (...rest) => {

    function checkStatus(response) {
        if(response.data.code!=0 && response.data.msg){
            Message.error(response.data.msg);
        }
        return response.data
    }

    function checkCode(res) {
        Message.error('请求出错,请稍后再试!');
        return res
    }

    let data=rest[2];
    let headers={'X-Requested-With': 'XMLHttpRequest'};
    let json={};

    if(rest[0].toLowerCase()!='get'){
        data= rest.length == 3 ? Qs.stringify(data) : data;
        headers= {
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        };
        json.data=data;
    }else{
        //data.t=new Date().getTime(); //去除get缓存
        json.params=data;
    }

    
    json.method=rest[0]; // 请求方式
    json.url=rest[1]; // 请求的地址
    json.timeout= 80000; // 超时时间, 单位毫秒
    json.headers=headers;

    return axios(json).then(checkStatus).catch(checkCode);

}


import {Ajax} from "../../utils"

export default {
    data:function(){
        return {
            list:[],
            checked:true,
        }
    },
    created(){
        this.comeIn();
    },
    methods: {
        async comeIn(){
            let postData = {
                checked: this.checked,
            };
            const data=await Ajax('get',`${this.$url}wpk/popups/list`,postData);
            if(data.code==0){
                console.log('返回成功')
            }
        },
    }
}