美文网首页
封装utils

封装utils

作者: 正版Figo | 来源:发表于2018-12-08 23:18 被阅读0次

    安装axios

    cnpm i axios --save-dev
    
    import axios from 'axios';
    import router from '@/router'
    /**
     * 封装get方法
     * @param url
     * @param data
     * @returns {Promise}
     */
    
    export function get(url, params = {}) {
        return new Promise((resolve, reject) => {
            axios.get(url, {
                params: params
            })
                .then(response => {
    
                    resolve(response.data);
                })
                .catch(err => {
                    reject(err)
                })
        })
    }
    
    
    /**
     * 封装post请求
     * @param url
     * @param data
     * @returns {Promise}
     */
    
    export function post(url, data = {}) {
        return new Promise((resolve, reject) => {
            axios.post(url, data)
                .then(response => {
                    resolve(response.data);
                }, err => {
                    reject(err)
                })
        })
    }
    
    /**
    * 封装patch请求
    * @param url
    * @param data
    * @returns {Promise}
    */
    
    export function patch(url, data = {}) {
        return new Promise((resolve, reject) => {
            axios.patch(url, data)
                .then(response => {
                    resolve(response.data);
                }, err => {
                    reject(err)
                })
        })
    }
    
    /**
    * 封装put请求
    * @param url
    * @param data
    * @returns {Promise}
    */
    
    export function put(url, data = {}) {
        return new Promise((resolve, reject) => {
            axios.put(url, data)
                .then(response => {
                    resolve(response.data);
                }, err => {
                    reject(err)
                })
        })
    }
    
    /**
    * 封装delete请求
    * @param url
    * @param data
    * @returns {Promise}
    */
    export function del(url, params = {}) {
        return new Promise((resolve, reject) => {
            axios.delete(url, {
                params: params
            })
                .then(response => {
                    resolve(response.data);
                })
                .catch(err => {
                    reject(err)
                })
        })
    }
    
    

    使用
    在main.js里写上

    import { post, get, patch, put, del } from './js/util'
    
    //定义全局变量
    Vue.prototype.$post = post;
    Vue.prototype.$get = get;
    Vue.prototype.$patch = patch;
    Vue.prototype.$put = put;
    Vue.prototype.$delete = del;
    

    相关文章

      网友评论

          本文标题:封装utils

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