vue 网络请求数据封装

本文详细介绍了如何在Vue.js应用中进行网络请求的数据封装,包括设置axios基础配置、创建axios实例、拦截器的使用以及如何在组件中调用封装后的API,提升代码复用性和可维护性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<script type="text/javascript">
    // 配置API接口地址
    const baseUrl = '';

    // 引入 弹窗组件
    var modal = weex.requireModule('modal');
    // 引入 请求数据组件
    var stream = weex.requireModule('stream');

    // 自定义判断元素类型JS
    function toType (obj) {
        return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
    }

    //==============
    // 参数过滤函数
    //==============
    function filterNull (o) {
        for (var key in o) {
            if (o[key] === null) {
                delete o[key]
            }
            if (toType(o[key]) === 'string') {
                o[key] = o[key].trim()
            } else if (toType(o[key]) === 'object') {
                o[key] = filterNull(o[key])
            } else if (toType(o[key]) === 'array') {
                o[key] = filterNull(o[key])
            }
        }
        return o
    }

    //=========
    // 工具方法
    //=========
    function toParams(obj) {
        var param = ""
        for(const name in obj) {
            if(typeof obj[name] != 'function') {
                param += "&" + name + "=" + encodeURI(obj[name])
            }
        }
        return param.substring(1)
    };

    //============
    // 接口处理函数
    //============
    function apiStream (method, url, params, success, failure) {
        // 过滤参数
        if (params) {
            params = filterNull(params)
        }

        /*** stream ***/
        if(method === 'GET'){
            console.log("进入了get方法")
            // GET 方法
            stream.fetch({
                method: 'GET',
                type: 'text',
                url: baseUrl + url + toParams(params)
            }, function(res) {
                if (res.ok) {
                    // 解密
                    let currentData = jwtdecode.decode(res.data, 'michahzdee2016', 'HS256');
                    success(currentData);
                }else {
                    modal.toast({
                        message: '请求失败,请检查网络!',
                        duration: 2
                    })
                }
            })
        }else if(method === 'POST'){
            // POST 方法
            stream.fetch({
                method: 'POST',
                type: 'text',
                url: baseUrl + url,
                headers: {'Content-Type':'application/x-www-form-urlencoded'},
                body: toParams(params)
            }, function(res) {
                if (res.ok) {
                    // 解密
                    let currentData = jwtdecode.decode(res.data, 'michahzdee2016', 'HS256');
                    success(currentData);
                }else {
                    modal.toast({
                        message: '请求失败,请检查网络!',
                        duration: 2
                    })
                }
            },function(progress) {
                //
            })
        }
    };

    //========================
    // 返回在vue模板中的调用接口
    //========================
    export default {
        // get方法
        get: function (url, params, success, failure) {
            return apiStream('GET', url, params, success, failure)
        },
        // post方法
        post: function (url, params, success, failure) {
            return apiStream('POST', url, params, success, failure)
        },
        // 用于查看域名 || 服务器地址
        globalHttpUrl:baseUrl
    }

</script>

使用

import global from './common.vue'


global.get('/api/user/channel/downloadInfo/get', params, function(data) {

      })
      this.COMMON.commonFun()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值