Uniapp + Vue3 封装请求工具挂载全局

新建request.js工具类

复制代码
const http = {
	// baseUrl 地址
	baseUrl: 'http://localhost:8080',

	// 请求方法
	request(config) {
		// config:请求配置对象,具体参照uniapp文档
		config = beforeRequest(config)
		// 请求地址拼接
		config.url = this.baseUrl + config.url
		// 异步请求
		return new Promise((resolve, reject) => {
			uni.request(config).then(res => {
				// 响应拦截
				const response = beforeResponse(res)
				resolve(response)
			}).catch(err => {
				errorHandle(err)
				reject(err)
			})
		})

	},
	get(url, data, auth, loading) {
		/*
		url:接口地址
		data:查询参数
		auth:请求是否携带token进行认证(true/false)
		method:请求方式
		*/
		return this.request({
			url: url,
			data: data,
			auth: auth,
			timeout: 10000,
			method: 'GET',
			loading: loading
		})
	},
	post(url, data, auth) {
		/*
		url:接口地址
		data:请求体参数
		auth:请求是否携带token进行认证(true/false)
		method:请求方式
		*/
		return this.request({
			url: url,
			data: data,
			auth: auth,
			timeout: 10000,
			method: 'POST'
		})
	},
	put(url, data, auth) {
		/*
		url:接口地址
		data:请求体参数
		auth:请求是否携带token进行认证(true/false)
		method:请求方式
		*/
		return this.request({
			url: url,
			data: data,
			auth: auth,
			timeout: 10000,
			method: 'PUT'
		})
	},
	delete(url, data, auth) {
		/*
		url:接口地址
		auth:请求是否携带token进行认证(true/false)
		method:请求方式
		*/
		return this.request({
			url: url,
			auth: auth,
			timeout: 10000,
			method: 'DELETE'
		})
	}
}

// 请求拦截器
const beforeRequest = (config) => {
	// 请求之前拦截操作
	console.log('请求拦截器', config)
	if (!config.loading) {
		uni.showLoading({
			title: '拼命请求中',
			mask: true,
		})
	} else {
		uni.showLoading({
			title: config.loading,
			mask: true,
		})
	}
	config.header = {}
	if (config.auth && config.auth != undefined) {
		// 请求头中添加token
		if (uni.getStorageSync('token')) {
			// Authorization    Bearer   根据情况修改
			config.header['Authorization'] = 'Bearer ' + uni.getStorageSync('token')
		} else {
			// 为登陆则跳转登陆 重定向
			uni.navigateTo({
				url: '/pages/index/index'
			})
		}
	}
	return config
}

// 响应拦截器
const beforeResponse = (response) => {
	// 请求之后操作
	console.log('响应拦截器', response)
	setTimeout(()=>{
		uni.hideLoading();
	},2000)
	// 判断请求返回的状态码
	if (response.status !== 200 && response.status !== 201 && response.status !== 204) {
		// 给出对应的提示
		if (response.data.error) {
			uni.showToast({
				title: response.data.error.toString(),
				icon: 'none',
				duration: 2000
			})
		}
	}
	return response
}

// 请求异常处理器
const errorHandle = ((err) => {
	console.log('请求异常', err)
})

export default http

在main文件中全局挂载、

复制代码
// 导入封装的请求对象
import http from '@/util/request.js'
app.config.globalProperties.$http = http

在vue页面中使用

复制代码
import type { ComponentInternalInstance } from 'vue'
const { proxy } = getCurrentInstance() as ComponentInternalInstance


// 使用默认的loading
const response = await proxy?.$http.get('/auth/tenant/list')
// 自定义的loading
const response1 = await proxy?.$http.get('/auth/tenant/list',null,null,'loading')

备注:Vue3不可以像vue2那样子通过this对象去调用全局挂载对象,需要使用 getCurrentInstance 方法获取proxy 对象。

运行结果:

相关推荐
lolo大魔王36 分钟前
Gin 框架响应格式与 HTML 模板渲染完整实战教程
前端·html·gin
llz_1123 小时前
web-第二次课后作业
前端·后端·web
vipbic8 小时前
别再把“做个H5”挂嘴边了:这个词,官方压根就没有定义过
前端
ZC跨境爬虫9 小时前
跟着 MDN 学CSS day_39:(Flexbox 弹性盒子核心机制)
前端·css·ui·html·tensorflow
小陈同学呦9 小时前
前端如何处理订单状态导航的数据竞态问题
前端·javascript
开发者每周简报10 小时前
网海三部曲·无名宗师传
javascript·人工智能
喵个咪10 小时前
GoWind Toolkit 前端代码生成|Vue3(ElementPlus/Vben)、React(AntDesign)全自动一键生成教程
前端·vue.js·react.js
摆烂大大王11 小时前
玩转 OpenClaw:用 TaskFlow + Heartbeat 打造自动化工作流
前端·人工智能·自动化
zhangxingchao11 小时前
AI 大模型核心六:量化、Workflow 与 Agent、多轮 RAG
前端·人工智能·后端
梦想的颜色12 小时前
TypeScript 完全指南(上):从零开始掌握类型系统
前端·typescript