Vue基于Axios网络请求封装

结构
api.js 将所有的接口统一管理
request.js 对网络请求进行了封装操作
image.png
封装代码
api.js

//api地址
const HOST = "http://xxx.com";
const API = HOST + "/api/public/";

const Apis = {
    // 产品
    getProduct: API + 'product',
    // 微信购买
    wxPay: API + 'weixinPay',
}
export default Apis

request.js

import Apis from "./api";
import axios from 'axios'
import {Message} from 'element-ui';

const METHOD = {
    GET: 'get',
    POST: 'post'
}
/**
 * 网络请求
 * @param method 方法
 * @param url 接口地址
 * @param params 参数
 * @param showError 是否展示错误信息
 * @returns {Promise<any>}
 */
// 错误和失败信息都在这里进行处理,界面中调用的时候只处理正确数据即可
function request(method, url, params, showError) {
    if (showError || showError == undefined){ // 是否展示错误信息
        showError = true;
    }else {
        showError = false;
    }
    return new Promise((resolve, reject) => {
        axios({
            method: method,
            url: url,
            params: params
        }).then((res) => {
            if (res.data.code == 0) { // 0 是请求成功
                resolve(res.data.data);
            } else { // 其他情况返回错误信息,根据需要处理
                reject(res.data);
                if (showError){
                    Message.error(res.data.message);
                }
            }
        }).catch(() => {
            if (showError){
                Message.error('请求失败,请稍后再试');
            }
        });
    });
}

/**
 * 图片上传
 * @param url 地址
 * @param params 参数 FormData
 * @param showError 是否展示错误
 * @returns {Promise<any>}
 */
function uploadRequest(url, params, showError) {
    if (showError || showError == undefined){
        showError = true;
    }else {
        showError = false;
    }
    let config = {
        headers: { "Content-Type": "multipart/form-data" },
    }
    return new Promise((resolve, reject) => {
        axios.post(url,params,config).then((res) => {
            if (res.data.code == 0) {
                resolve(res.data.data);
            } else {
                reject(res.data);
                if (showError){
                    Message({
                        type: 'error',
                        message: res.data.message,
                        duration: 1000
                    });
                }
            }
        }).catch(() => {
            if (showError){
                Message({
                    type: 'error',
                    message: '请求失败,请稍后再试',
                    duration: 1000
                });
            }
        });
    });
}

function get(url, params, showError) {
    return request(METHOD.GET, url, params, showError);
}

function post(url, params, showError) {
    return request(METHOD.POST, url, params, showError);
}

function upload(url, params, showError) {
    return uploadRequest(url, params, showError);
}
const API = {
    // 产品
    getProduct: (params) => post(Apis.getProduct, params),
    // 微信购买
    wxPay: (params) => post(Apis.wxPay, params),
}

function install(Vue) {
    Vue.prototype.$request = API;
}
export default install

具体使用
main.js 引入

import VueRequest from './js/vuex/request'
Vue.use(VueRequest);

xxx.vue界面使用

<script>
    export default {
        name: "xxx",
        data() {
            return {
                tableData: []
            }
        },
        mounted() {
            this.loadModuleData();
        },
        methods: {
            /**
             * 产品数据获取
             */
            loadProductData() {
                let params = {
                    uid: xxx
                }
                this.$request.getProduct(
                    params
                ).then((data)=>{ // 直接拿到的就是成功数据,其他情况封装的时候统一处理
                    data.forEach(data => {
                        this.tableData.push({
                            id: data.id || '',
                            name: data.name || '',
                            desc: data.desc || '',
                        })
                    })
                });
            },
           // 文件上传
          uploadFile(file){
                let params = new FormData();
                params.append('file', file);
                params.append('ucenter_id', this.$store.getUserId());
                this.$request.uploadImage(
                    uploadData
                ).then((res) => {
                    console.log(res);
                });
            }
        }
    }
</script>

Axios 易用、简洁且高效的http库
Promise详解
Element一套为开发者、设计师和产品经理准备的基于Vue的桌面端组件库

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dev _

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值