vue3 +ts 如何安装封装axios
2023-06-13 09:18:15 时间
以vite创建的项目,
vue3使用axios。
使用ts二次封装axios
访问接口,并调用接口。vue3
安装封装axios
,其实和vue2的大差不差。只是在ts和js上,有些区别。
为什么封装axios
- 求头能统一处理
- 便于接口的统一管理
- 解决回调地狱
- 配置拦截器,给不同的实例配置不同的拦截器,支持以对象形式接受多个拦截器配置
安装axios
npm install axios
引入插件
在使用的文件中引入
import axios from "axios";
封装request
先在 src 下创建一个 utils文件夹,并添加一个 request.ts 文件
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
class HttpRequest {
private readonly baseUrl: string;
constructor() {
this.baseUrl = 'http://localhost:8080'
}
getInsideConfig() {
const config = {
baseURL: this.baseUrl,// 所有的请求地址前缀部分(没有后端请求不用写)
timeout: 80000, // 请求超时时间(毫秒)
withCredentials: true,// 异步请求携带cookie
// headers: {
// 设置后端需要的传参类型
// 'Content-Type': 'application/json',
// 'token': x-auth-token',//一开始就要token
// 'X-Requested-With': 'XMLHttpRequest',
// },
}
return config
}
// 请求拦截
interceptors(instance: AxiosInstance, url: string | number | undefined) {
instance.interceptors.request.use(config => {
// 添加全局的loading..
// 请求头携带token
return config
}, (error: any) => {
return Promise.reject(error)
})
//响应拦截
instance.interceptors.response.use(res => {
//返回数据
const { data } = res
console.log('返回数据处理', res)
return data
}, (error: any) => {
console.log('error==>', error)
return Promise.reject(error)
})
}
request(options: AxiosRequestConfig) {
const instance = axios.create()
options = Object.assign(this.getInsideConfig(), options)
this.interceptors(instance, options.url)
return instance(options)
}
}
const http = new HttpRequest()
export default http
封装接口
在api的文件夹中,新建一个api的ts文件。
注意:因为get请求的参数需要
params
,它是即将与请求一起发送的 URL 参数,为了简写采用了ES6的解构,就是把下面的params
解构,只有get 请求需要加多一层params
。 其它请求,如 post 等请求等就不用解构,形参是什么都行。
案例
src文件夹下新建api文件夹,新建api.ts文件,里面写你请求后台的接口,比如我这里的请求地址是/test, 加上axios的baseURL,完整的请求路径就是http://localhost:8080/test
import http from '../utils/request'
//get有值
export function getTest(params: any) {
return http.request({
url: '/test',
method: 'get',
params
})
}
//get无值
export function (params: any) {
return http.request({
url: '/test',
method: 'get',
params
})
}
使用
请求的组件上使用
import { ref, onMounted } from "vue";
import { getFileList } from "../../api/index";
export default {
setup() {
onMounted(() => {
getTest().then((res: any) => {
console.log(res);
});
});
},
};
相关文章
- Vue3源码01 : 代码管理策略-monorepo
- vue3配置jsx
- Vue3和@types/node的类型不兼容问题
- Vue3源码解读之patch
- 兼容vue2和vue3版本的插件实现过程
- vue报错cannot read property_vue3 ref 数组
- Vue3局部组件
- 2021年最佳VUE3 UI框架推荐
- 用Vue3开发,这几个工具你得知道。摸鱼不能耽误
- Vue3学习笔记(四)——组件、生命周期
- webstrom 打开vue3项目时 不识别组合式API的解决办法
- vue3+elementplus(vuex)增删改查
- vite+vue3搭建uniapp开发环境
- Vue3学习笔记 用朴素的语言理解大名鼎鼎的响应式
- Vue3学习笔记Day10 如何使用Vuex进行数据跨组件交互?
- 基于Vue3+TS的Monorepo前端项目架构设计与实现
- Vue3学习笔记
- VUE3+ts安装elementplus
- 在VUE3项目中添加使用永久免费H5直播点播播放器SkeyeWebPlayer.js及问题