vue3+ts Axios封装与使用
创建完vue3 项目后
新版本:动态控制是否显示加载动画。是否需要判断重复请求。https://www.cnblogs.com/lovejielive/p/17676856.html
一,安装Axios与Element Plus
Axios安装
npm install axios
Element Plus 安装
官网入口:https://element-plus.gitee.io/zh-CN/
npm install element-plus --save
二,在src 目录下创建 api 文件夹和 utils 文件夹
api 文件夹下 封装 Axios封装 与 请求配置
utils 文件夹下 operate.ts 配置接口地址 与其他全局ts
Axios封装
api文件夹下 创建 request-wrapper.ts Axios封装


/*
* @description: 请求封装
* @Author: Jay
* @Date: 2022-06-08 11:41:36
* @LastEditors: Jay
* @LastEditTime: 2022-06-08 15:29:38
*/
// 导入axios
import axios, { AxiosInstance, AxiosRequestConfig } from "axios";
// 使用element-ui ElMessage做消息提醒 ElLoading加载
import { ElMessage, ElLoading } from "element-plus";
//请求头
import operate from '@/utils/operate'; //加载配置
let loadingInstance: any,
requestNum: number = 0,
loading: boolean = true; //加载动画
const addLoading = () => {
// 防止重复弹出
requestNum++;
if (requestNum == 1) {
loadingInstance = ElLoading.service({ fullscreen: true });
}
} // 关闭 加载动画
const cancelLoading = () => {
requestNum--;
// 关闭 加载动画
if (requestNum === 0) loadingInstance?.close();
} //请求配置
export const createAxios = (
config?: AxiosRequestConfig,
): AxiosInstance => {
const instance = axios.create({
//请求头
baseURL: operate.baseUrl(),
// baseURL: '/api',
//超时配置
timeout: 1000,
//跨域携带cookie
withCredentials: true,
// 自定义配置覆盖基本配置
...config,
}); // 添加请求拦截器
instance.interceptors.request.use(
function (config: any) {
// console.log("请求拦截器config:", config);
//加载动画
if (loading) addLoading(); //判断是否有token 根据自己的需求判断
let token = config.token;
console.log("判断是否有token", token)
if (token != undefined) {
//如果要求携带在参数中
config.params = Object.assign({}, config.params, token)
// 如果要求携带在请求头中
// config.headers = Object.assign({}, config.headers, operate.uploadParameters())
}
return config;
},
function (error) {
// 请求错误
return Promise.reject(error)
}
) // 添加响应拦截器
instance.interceptors.response.use(
function (response) {
// console.log("响应拦截器response:", response);
// 关闭加载 动画
if (loading) cancelLoading();
//返回参数
return response.data;
},
function (error) {
// 关闭加载 动画
if (loading) cancelLoading();
/***** 接收到异常响应的处理开始 *****/
if (error && error.response) {
// 1.公共错误处理
// 2.根据响应码具体处理
switch (error.response.status) {
case 400:
error.message = '错误请求'
break;
case 401:
error.message = '未授权,请重新登录'
break;
case 403:
error.message = '拒绝访问'
break;
case 404:
error.message = '请求错误,未找到该资源'
window.location.href = "/NotFound"
break;
case 405:
error.message = '请求方法未允许'
break;
case 408:
error.message = '请求超时'
break;
case 500:
error.message = '服务器端出错'
break;
case 501:
error.message = '网络未实现'
break;
case 502:
error.message = '网络错误'
break;
case 503:
error.message = '服务不可用'
break;
case 504:
error.message = '网络超时'
break;
case 505:
error.message = 'http版本不支持该请求'
break;
default:
error.message = `连接错误${error.response.status}`
}
} else {
// 超时处理
if (JSON.stringify(error).includes('timeout')) {
error.message = '服务器响应超时,请刷新当前页'
} else {
error.message = '连接服务器失败'
}
}
//提示
ElMessage.error(error.message)
/***** 处理结束 *****/
return Promise.resolve(error.response)
}
) return instance;
}
Axios封装
api文件夹下 创建 api.ts 接口配置


/*
* @description: 请求接口 配置
* @Author: Jay
* @Date: 2022-06-08 10:41:36
* @LastEditors: Jay
* @LastEditTime: 2022-06-08 14:29:38
*/
//导入 Axios 请求
import { createAxios } from './request-wrapper'
const request = createAxios();
//其他配置
// import operate from '@/utils/operate'; // get 请求
export const exportGet = (params: any): Promise<any> =>
request.get("/api/search/get/web", { params }); // post 请求
export const exportPost = (data: any) =>
//请求 token 添加
// request.post("/export", Object.assign(data, { token: operate.isToken() }));
request.post("/export", data); /*
请求配置与使用 * POST 请求 方式
export const 名字 = (data: any) =>
request.post("接口", data, {
直接为空
注:只能配置 AxiosRequestConfig 里有的参数名 可不用配置
}); * GET 请求 方式
export const 名字 = (params: any): Promise<any> =>
request.get("接口", { params }); *使用 方法
*引入
import {
名字
} from "../api/api"
*生命周期中 请求
名字({请求参数}).then((res) => {
console.log(res)
})
*/
接口配置
开始请求


<script lang="ts">
import {
exportGet,
exportPost
} from "../api/api"
import {
defineComponent,
onMounted
} from "vue"; export default defineComponent({
setup() {
onMounted(() => {
//get 请求
exportGet({
csrf_token: '5555'
}).then((res) => {
console.log(res)
}) // post 请求
exportPost({
csrf_token: '5555'
}).then((res) => {
console.log(res)
})
}) return {};
},
});
</script>
测试 结果:
三,全局配置JS
operate.ts 创建


/*
* @description: 自定义 ts
* @Author: Jay
* @Date: 2022-06-08 13:22:07
* @LastEditors: Jay
* @LastEditTime: 2022-06-08 14:35:07
*/
// vuex 数据
import store from '../store/index' export default {
//接口地址
baseUrl: function () {
// console.log(process.env.NODE_ENV)
if (process.env.NODE_ENV == "development") {
//开发环境
return "development";
} else {
//正式环境
return "production";
}
}, //获取用户token
isToken: function () {
if (store.state.Authorization != '') {
return store.state.Authorization
}
return false;
}, /*
格式化时间 加上时分秒
num: 后台时间格式
type: 'YY-MM-DD'年月日 ,'HH-MM-SS'时分秒 ,不传 年月日时分秒
*/
happenTime: function (num: any, type: String) {
let date = new Date(num * 1000);
//时间戳为10位需*1000,时间戳为13位的话不需乘1000
let y: any = date.getFullYear();
let MM: any = date.getMonth() + 1;
MM = MM < 10 ? ('0' + MM) : MM; //月补0
let d: any = date.getDate();
d = d < 10 ? ('0' + d) : d; //天补0
let h: any = date.getHours();
h = h < 10 ? ('0' + h) : h; //小时补0
let m: any = date.getMinutes();
m = m < 10 ? ('0' + m) : m; //分钟补0
let s: any = date.getSeconds();
s = s < 10 ? ('0' + s) : s; //秒补0
if (type === 'YY-MM-DD') {
//年月日
return y + '-' + MM + '-' + d;
} else if (type === 'HH-MM-SS') {
//时分秒
return h + ':' + m + ':' + s;
} else {
//全部
return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
}
}, //性别
formSex: function (set: String | Number) {
const status: Object = {
"0": "男",
"1": "女"
}
let key: keyof Object;
for (key in status) {
//console.log(key, status[key])
if (key == set) {
return status[key];
}
}
return '未知'
}
}
operate.ts 创建
operate.ts 全局配置
在mian.ts 中
//全局 js
import operate from "./utils/operate"
app.config.globalProperties.$operate = operate
在页面中使用
<script lang="ts">
import {
getCurrentInstance,
onMounted
} from "vue"; export default defineComponent({
setup() {
//等于 vue this.
const {
proxy
} = getCurrentInstance() as any;
/*
as any 在最后 加上这个 就不会 报下面的错误
类型“ComponentInternalInstance | null”上不存在属性“proxy”。
*/ onMounted(() => {
console.log("性别为:",proxy.$operate.formSex(0))
}) return {};
},
});
</script>
最后结果
vue3+ts Axios封装与使用的更多相关文章
- vue3.0+vite+ts项目搭建-axios封装(六)
封装方式一 import axios from 'axios' import qs from 'qs' import { Toast } from 'vant' import Lockr from ' ...
- 基于Vue3+TS的Monorepo前端项目架构设计与实现
写在前面 你好,我是前端程序员鼓励师岩家兴!去年在另一个项目https://juejin.cn/post/7121736546000044046中,我向读者朋友们介绍了结合npm包管理工具yarn作v ...
- axios封装
前言 作为出入vue的小萌新,我在写请求的时候,也是毫不犹豫写了ajax,结果肯定是不行的... Vue 原本有一个官方推荐的 ajax 插件 vue-resource,但是自从 Vue 更新到 2. ...
- vue2.0 axios封装、vuex介绍
一.前言 博主也是vue道路上的行者,道行不深,希望自己的东西能对大家有所帮助.这篇博客针对 了解过vue基础,但是没有做过vue项目的童鞋.如果想看基础指令,可以看我之前的一篇博客,请点击 跳转, ...
- 把axios封装为vue插件使用
前言 自从Vue2.0推荐大家使用 axios 开始,axios 被越来越多的人所了解.使用axios发起一个请求对大家来说是比较简单的事情,但是axios没有进行封装复用,项目越来越大,引起的代码冗 ...
- vue项目搭建 (二) axios 封装篇
vue项目搭建 (二) axios 封装篇 项目布局 vue-cli构建初始项目后,在src中进行增删修改 // 此处是模仿github上 bailicangdu 的 ├── src | ├── ap ...
- 原生js上传图片遇到的坑(axios封装)
后台给我写了一个上传图片的接口,自己用form表单测试成功 接口可以正常跳转 测试的代码: <!doctype html> <html lang="en"> ...
- vue-cli3中axios如何跨域请求以及axios封装
1. vue.config.js中配置如下 module.exports = { // 选项... // devtool: 'eval-source-map',//开发调试 devServer: { ...
- axios interceptors 拦截 , 页面跳转, token 验证 Vue+axios实现登陆拦截,axios封装(报错,鉴权,跳转,拦截,提示)
Vue+axios实现登陆拦截,axios封装(报错,鉴权,跳转,拦截,提示) :https://blog.csdn.net/H1069495874/article/details/80057107 ...
- 【Vue】axios封装,更好的管理api接口和使用
在现在的前端开发中,前后端分离开发比较主流,所以在封装方法和模块化上也是非常需要掌握的一门技巧.而axios的封装也是非常的多,下面的封装其实跟百度上搜出来的axios封装或者axios二次封装区别不 ...
随机推荐
- xlookup与vlookup的区别
区别还是很大的,vlookup暂时扔不了.
- SpringBoot排查自动装配、Bean、Component、Configuration配置类
排除自动装配AutoConfiguration @SpringBootApplication( exclude = { DataSourceAutoConfiguration.class, Mybat ...
- MiniAuth 一个轻量 ASP.NET Core Identity Web 后台管理中间插件
MiniAuth 一个轻量 ASP.NET Core Identity Web 后台管理中间插件 「一行代码」为「新.旧项目」 添加 Identity 系统跟用户.权限管理网页后台系统 开箱即用,避免 ...
- Nginx 工作原理简介
在了解Nginx工作原理之前,我们先来了解下几个基本的概念 以及常见的I/O模型. 基本概念 同步:就是指调用方发起一个调用,在没有得到调用结果之前,该调用不返回.换句话说,也就是调用方发起一个调用后 ...
- 游戏开发进行中UE5引擎打不开后续
游戏每次启动都有个问题: 之前我实现了插件里的接口,但是已启动,关于接口这一块的就消失了,有些函数还在但是却是自定义事件,不是接口里的,Class Settings里面也提了 然后我把他改成了新的ch ...
- 为什么我@Value中明明显示了值,他却是null
今天尝试把一些重要东西写入application.yml里,结果在使用的时候发现value取不出来值原因有2个: 1.没有写@compent,没有把这个类交给spring管理 2.在service层n ...
- ComfyUI插件:ComfyUI layer style 节点(二)
前言: 学习ComfyUI是一场持久战,而ComfyUI layer style 是一组专为图片设计制作且集成了Photoshop功能的强大节点.该节点几乎将PhotoShop的全部功能迁移到Comf ...
- 【Java】项目采用的设计模式案例
先说一下业务需要: 做电竞酒店后台系统,第一期功能有一个服务申请的消息通知功能 就是酒店用户在小程序点击服务功能,可以在后台这边查到用户的服务需要 原本设计是只需要一张表存储这些消息,但是考虑设计是S ...
- 【Vue】Re18 Router 第五部分(KeepAlive)
一.KeepAlive概述 默认状态下,用户点击新的路由时,是访问新的组件 那么当前组件是会被销毁的,然后创建新的组件对象出来 如果某些组件频繁的使用,将造成内存空间浪费,也吃内存性能 所以需求是希望 ...
- 甄嬛霸气照 —— Chinese Queen