一、前言

最近开始入门Vue开发web我的项目,调试接口的时候抽时间将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 

4、具体应用

  • 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> 

5、情谊延长

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

作者:calary
链接:https://www.jianshu.com/p/0e6...
起源:简书
著作权归作者所有。商业转载请分割作者取得受权,非商业转载请注明出处。