美文网首页
Vue的Request

Vue的Request

作者: SWLB | 来源:发表于2019-01-22 17:53 被阅读0次

    目的:用一个API文件统一管理接口

    文件:src/aip/request.js

     import config from "../config/config";
    import axios from "axios";
    import {Loading} from "element-ui";
    import {Message} from 'element-ui';
    
    axios.interceptors.response.use(function (response) {
        // console.log("resopnse--------------------");
        // console.log(response);
        if (response.data.code === 9) {
            Message({
                type: 'error',
                message: '未授权的操作'
            });
            return 9;
        }
        return response;
    }, function (error) {
    
        // console.log("error--------------");
        // console.log(error.status);
        return error;
    });
    export default async (url = '', data = {}, type = 'GET', method = 'fetch') => {
        type = type.toUpperCase();
        url = config.host + url;
        //将对象解析成get后面?&形式的参数
        if (type === 'GET' || type === 'DOWNLOAD' || type === 'UPLOAD') {
            let dataStr = ''; //数据拼接字符串
            Object.keys(data).forEach(key => {
                //过滤空字段
                // if (data[key].length > 0 && data[key] !== undefined)
                dataStr += key + '=' + data[key] + '&';
            });
            if (dataStr !== '') {
                dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
                url = url + '?' + dataStr;
            }
        } else if (type == "RESTFUL") {
            url += data;
        }
        //请求服务加载
    
        const loading = Loading.service({
            body: document.getElementById("app"),
            fullscreen: true,
            lock: true,
            text: '数据拼命加载中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.2)',
            customClass: 'loading',
    
        });
    
        return new Promise((resolve, reject) => {
            switch (type) {
                case "UPLOAD": {
                    loading.close();
                    resolve(url);
                }
                    break;
                case "GET": {
                    axios.get(url).then(async (res) => {
                        loading.close();
                        resolve(res.data);
                    }).catch(async (err) => {
                        loading.close();
                        reject(err);
                    })
                }
                    break;
                case "POST": {
                    url = url + "?XDEBUG_SESSION_START=PHPSTORM";
                    axios.post(url, data).then(async (res) => {
                        loading.close();
                        resolve(res.data);
                    }).catch(async (err) => {
                        loading.close();
                        reject(err);
                    });
    
                }
                    break;
                case "DOWNLOAD": {
                    window.open(url);
                    loading.close();
                    resolve(url);
                }
                    break;
                case "RESTFUL":{
                    axios.get(url).then(async (res) => {
                        loading.close();
                        resolve(res.data);
                    }).catch(async (err) => {
                        loading.close();
                        reject(err);
                    })
                }
    
            }
    
        })
    };
    
    
    

    src/api/api.js

    import request from "./request";
    import config from "../config/config";
    /*
     example
     export const imgUpload = config.host + 'api/upload/img';
     export const addAdminUser = (data) => request('api/admin/addAdminUser',data,'post');
     export const workDownload = (data) => request('api/work/downloadZip', data, 'download');//下载的特殊用法
     export const workUpload = (data) => request('api/work/upload', data, "UPLOAD");
     export const companySoftUsageCount=(data)=>request("companysoftusage/",data,"restful");
    */
    
    
    export const CompanyList=()=>request("company");
    export const companySoftUsageCount=(data)=>request("companysoftusage/",data,"restful");
    

    src/components/CompanyList.vue

     import {CompanyList} from "../api/api";
    
        export default {
            name: "CompanyList",
            data() {
                return {
                    companyList: [],
                    companyListData:[],
                    keyword: ''
                }
            },
            async created() {
                this.companyList=this.companyListData = await CompanyList();
            },
            methods: {
                filterCompany: function () {
                    let _this = this;
                    this.companyList=this.companyListData.filter(function checkAdult(item) {
                        let index = item.c.indexOf(_this.keyword);
                        return index != -1;
                    })
                },
                enter(item){
                    this.$router.push({name:"companySoftUsageCount",params:{companyname:item.c}})
                }
            }
        }
    

    相关文章

      网友评论

          本文标题:Vue的Request

          本文链接:https://www.haomeiwen.com/subject/uljrjqtx.html