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 对象。

运行结果:

相关推荐
多多*10 分钟前
2026年最新 测试开发工程师相关 Linux相关知识点
java·开发语言·javascript·算法·spring·java-ee·maven
Laurence11 分钟前
从零到一构建 C++ 项目(IDE / 命令行双轨实现)
前端·c++·ide
会编程的土豆19 分钟前
简易植物大战僵尸游戏 JavaScript版之html
javascript·游戏·html
雯0609~21 分钟前
hiprint-官网vue完整版本+实现客户端配置+可实现直接打印(在html版本增加了条形码、二维码拖拽等)
前端·javascript·vue.js
VT.馒头21 分钟前
【力扣】2705. 精简对象
javascript·数据结构·算法·leetcode·职场和发展·typescript
GISer_Jing23 分钟前
构建高性能Markdown引擎开发计划
前端·aigc·ai编程
摘星编程27 分钟前
在OpenHarmony上用React Native:Switch禁用状态
javascript·react native·react.js
CHU72903541 分钟前
生鲜商城小程序前端功能版块:适配生鲜采购核心需求
前端·小程序
huangyiyi666661 小时前
Vue + TS 项目文件结构
前端·javascript·vue.js
0思必得01 小时前
[Web自动化] Selenium处理Cookie
前端·爬虫·python·selenium·自动化