当前位置: 首页 > news >正文

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) {// 请求头中添加tokenif (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 对象。

运行结果:

相关文章:

  • windows平台配置vsCode_CMake_Clang/LLVM_ninja环境与测试
  • 堆与二叉树(下)
  • 深度学习 | 基础卷积神经网络
  • 智能优化算法应用:基于蛇优化算法3D无线传感器网络(WSN)覆盖优化 - 附代码
  • C语言沉浸式刷题【C语言必刷题】
  • rk3588 之启动
  • 初识QT(上篇):What Qt
  • 【顶级快刊】IEEE(Trans),审稿快仅2个月录用,入选CCF-B,现在投最快!
  • ZKP Mathematical Building Blocks (2)
  • Spring MVC 方法中添加参数、HttpServletRequest 和 HttpServletResponse 对象
  • Netty-4-网络编程模式
  • 【clickhouse】在CentOS中离线安装clickhouse
  • 代码随想录算法训练营 | day60 单调栈 84.柱状图中最大的矩形
  • 每日一题(LeetCode)----栈和队列--滑动窗口最大值
  • centos 安装 Miniconda
  • 【140天】尚学堂高淇Java300集视频精华笔记(86-87)
  • 【前端学习】-粗谈选择器
  • Android 控件背景颜色处理
  • egg(89)--egg之redis的发布和订阅
  • Iterator 和 for...of 循环
  • JAVA 学习IO流
  • Javascript 原型链
  • nodejs:开发并发布一个nodejs包
  • PHP 的 SAPI 是个什么东西
  • QQ浏览器x5内核的兼容性问题
  • SpringBoot 实战 (三) | 配置文件详解
  • vue自定义指令实现v-tap插件
  • 经典排序算法及其 Java 实现
  • 使用docker-compose进行多节点部署
  • 限制Java线程池运行线程以及等待线程数量的策略
  • 消息队列系列二(IOT中消息队列的应用)
  • 协程
  • 一道面试题引发的“血案”
  • LIGO、Virgo第三轮探测告捷,同时探测到一对黑洞合并产生的引力波事件 ...
  • Mac 上flink的安装与启动
  • puppet连载22:define用法
  • 大数据全解:定义、价值及挑战
  • ​ ​Redis(五)主从复制:主从模式介绍、配置、拓扑(一主一从结构、一主多从结构、树形主从结构)、原理(复制过程、​​​​​​​数据同步psync)、总结
  • ###项目技术发展史
  • $ git push -u origin master 推送到远程库出错
  • (2009.11版)《网络管理员考试 考前冲刺预测卷及考点解析》复习重点
  • (保姆级教程)Mysql中索引、触发器、存储过程、存储函数的概念、作用,以及如何使用索引、存储过程,代码操作演示
  • (二)c52学习之旅-简单了解单片机
  • (附源码)springboot建达集团公司平台 毕业设计 141538
  • (一)Dubbo快速入门、介绍、使用
  • (一)Mocha源码阅读: 项目结构及命令行启动
  • (转载)从 Java 代码到 Java 堆
  • .NET CORE Aws S3 使用
  • .NET 中 GetHashCode 的哈希值有多大概率会相同(哈希碰撞)
  • .NET/C# 编译期间能确定的相同字符串,在运行期间是相同的实例
  • .NET/C# 反射的的性能数据,以及高性能开发建议(反射获取 Attribute 和反射调用方法)
  • .net6+aspose.words导出word并转pdf
  • /run/containerd/containerd.sock connect: connection refused
  • @Transactional 竟也能解决分布式事务?
  • @拔赤:Web前端开发十日谈