uniapp封装公共请求方法

1、项目更目录下新建common文件夹,再创建request.js文件
2、打开request.js文件,开始写封装的代码

const request = (url = '', date = {}, titles = '加载中',type = 'POST', header = {
}) => {
    return new Promise((resolve, reject) => {
        uni.showLoading({
            title: titles
        });
        uni.request({
            method: type,
            url: url,
            data: date,
            header: header,
            dataType: 'json',        
        }).then((response) => {
            uni.hideLoading();
            uni.stopPullDownRefresh();
            let [error, res] = response;
            if(res.data.code == 0){
                uni.showToast({
                    title:res.data.msg,
                    duration: 1000,
                    success:function(){
                        uni.hideLoading();
                    }
                });
                setTimeout(function () {
                    resolve(res.data);
                }, 1000);
            }else if(res.data.code == 1){
                uni.showToast({
                    title:res.data.msg.MSG,
                    image:'../../static/public/guanbi_i.png',
                    duration: 2000,
                    success:function(){
                        uni.hideLoading();
                    }
                });
            }else {
                uni.showToast({
                    title:res.data.msg,
                    image:'../../static/public/guanbi_i.png',
                    duration: 2000,
                    success:function(){
                        uni.hideLoading();
                    }
                });
            }
        }).catch(error => {
            uni.hideLoading();
            uni.stopPullDownRefresh();
            let [err, res] = error;
            reject(err)
        })
    });
}
export default request

3、在main.js全局注册

import request from 'common/request.js'
Vue.prototype.$request = request

4、页面调用

this.$request('url地址', {
    //参数放在这里
    'id':1,
}).then(res => {
    // 打印调用成功回调
    console.log('返回正确回调')
})
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容