uniapp 二次封装uni.request方法

common -> utils.js

class Utils{

constructor(){
	this.baseUrl = 'http://101.34.77.85:3300/pz'
}
getUserInfo(){
	// 调用登录的Api
	uni.login({
		seccess:function(res){
			console.log(res)
		}
	})
}

request(option = {
	showLoading:false
}){
	// 判断url是否存在
	if(!option.url){
		return false
	}
	if(option.shaowLoading){
		this.showLoading()
	}
	uni.request({
		url:this.baseUrl + option.url,
		data:option.data ? option.data : {},
		header:option.header ? option.header : {},
		method: option.method ? option.method : 'GET',
		success:(response) => {
			uni.hideLoading()
			// 后端返回的数据异常(正常是10000,每个人可能不一样)
			if(response.data.code != 10000){
				// 	将失败的结果返回失去
				if(option.fail && typeof option.fail == 'function'){
					option.fail(response)
					}
				} else {
					// 将成功的结果返回
					if(option.success && typeof option.success == 'function'){
						option.success(response.data)
					}
				}
			}
		},
		fail:response => {
			uni.hideLoading()
			console.log(response)
		}
	})
}

// 创建加载的loading效果
showLoading(){
	const isShowLoading = uni.getStorageSync('isShowLoading')
	if(!isShowLoading){
		uni.hideLoading()
		uni.setStorageSync('isShowLoading',false)
	}
	uni.showLoading({
		title:'加载中...',
		complete:function(){
			uni.setStorageSync('isShowLoading',true)
		},
		fail:function(){
			uni.setStorageSync('isShowLoading',false)
		}
	})
}
}
export default new utils()

App.vue页面

<script>
	import Utils from './common/utils.js'
	export default{
		globalData:{
			utils:Utils
		}
	}
</script>

在页面中使用:

import { onLoad } from '@dcloudio/uni-app'

// 导入获取App.vue的数据
const app = getApp()
onLoad(()=>{
	console.log(app.globalData.utils.getUserInfo())
})
const

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值