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

9 篇文章 0 订阅
文章介绍了如何创建一个uniapp环境下的request.js工具类,包含基础的GET、POST等HTTP请求方法,以及请求拦截、响应拦截和错误处理功能,适用于Vue3中全局使用并支持自定义loading。
摘要由CSDN通过智能技术生成

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

运行结果:

  • 12
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
UniApp中使用Vue3进行接口请求封装可以按照以下步骤进行。 1. 创建一个文件,例如`api.js`,用于定义接口请求相关的函数。 ```javascript import { createApp } from 'vue' import { reactive } from 'vue' const app = createApp({}) const state = reactive({ // 定义一些全局请求相关配置,如baseURL等 baseURL: 'https://api.example.com', timeout: 10000, }) // 定义接口请求函数 export const request = async (config) => { config.url = state.baseURL + config.url config.timeout = state.timeout try { const response = await app.config.globalProperties.$http(config) return response.data } catch (error) { throw new Error(error) } } ``` 2. 在`main.js`中进行拦截器和全局挂载的配置。 ```javascript import { createApp } from 'vue' import App from './App.vue' const app = createApp(App) // 在app.config.globalProperties上挂载$http方法,用于发送请求 app.config.globalProperties.$http = (config) => { // 在这里可以使用uni.request或者其他库进行实际的请求发送 // 返回一个Promise对象 } app.mount('#app') ``` 3. 在需要使用接口的地方,引入`api.js`文件并调用接口请求函数。 ```javascript import { request } from './api.js' // 调用接口请求函数 request({ url: '/example', method: 'get', }).then((response) => { console.log(response) }).catch((error) => { console.error(error) }) ``` 通过以上步骤,你可以在UniApp中使用Vue3进行接口请求封装。当然,你可以根据具体的需求进行更多的定制和封装
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值