刚完成了vue项目,在项目中用到了axios+typescript封装,感觉比较重要,分享给大家,希望对大家有帮助!
1.首先在src中新建一个utils文件夹,在该文件中新建三个ts(也可以是js)文件,如下图

2.在http.ts中自定义 axios 实例添加请求和响应拦截器
- 可以自行配置跨域处理方式
- 拦截器学习 使用说明 · Axios 中文说明 · 看云
import axios, { AxiosInstance, AxiosResponse, AxiosError, AxiosRequestConfig } from "axios";
const instance: AxiosInstance = axios.create({
/** 如果是使用的CORS处理跨域,这里应该设置为 http://127.0.0.1:81 */
/** 我们这里使用的是Proxy处理跨域,所以设置为 /api 来匹配跨域规则即可 */
baseURL: "/api",
timeout: 5000,
headers: {
// 'Content-Type': 'application/json',
Authorization: "token" /** 假设一下 ,假的,没用 */,
},
// `transformRequest` 允许在向服务器发送前,修改请求数据
// 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
// 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
// transformRequest: [function (data) {
// // 对 data 进行任意转换处理
// return Qs.stringify(data);
// }],
});
//你可以放心的进行全局配置 ,非常方便,为后续完善项目做准备
// 添加请求拦截器
instance.interceptors.request.use(
function (config: AxiosRequestConfig) {
// 在发送请求之前做些什么
return config;
},
function (error: AxiosError) {
// 对请求错误做些什么
return Promise.reject(error);
}
);
// 添加响应拦截器
instance.interceptors.response.use(
function (response: AxiosResponse) {
// 对响应数据做点什么
//比如:你在进行删除操作的时候,返回的是 {code:401, msg:'请登录'}
console.log('interceptors', response.data);
return response.data;
},
function (error: AxiosError) {
// 对响应错误做点什么
return Promise.reject(error);
}
);
export default instance;
3.在api.ts导入http.ts 拦截器,并对项目使用到的请求进行封装并导出
import { AxiosRequestConfig } from "axios";
import instance from "./http";
import { userRegisterI, homeSentenceI, userCenterI, homeislikeI, homeComInfoI, homecomInfoI, setcomToInfoI, clidDataI, searchDataI } from "./type";
//已经配置了baseUrl,所以这里直接写路由即可,不用 /api
/** 登录 */
export const userLogin = (userInfo: LoginData) => {
return instance.post('/login', userInfo);
};
export const userRegister = (userInfo: LoginData) => {
return instance.post('/register', userInfo);
};
//首页句子内容
export const homeSentence = (type: homeSentenceI) =>
instance.get("/homesentence", {
params: type
});
//首页 谁喜欢了哪个句子
export const homeSentenceLike = () =>
instance.get("/homesentencelike");
//首页 点击喜欢按钮
export const homeSentenceisLike = (islike: homeislikeI) =>
instance.post("/homesentenceislike", islike);
4.在type.ts文件中定义请求参数的类型约束(js开发可以省略),并在api.ts中导入并使用
import { AxiosRequestConfig, AxiosResponseHeaders } from "axios";
import { ref } from "vue";
import type { FormInstance } from "element-plus";
export interface lofinFormInt {
username: string,
password: string,
repasswd: string;
}
export class MyData {
ruleForm: lofinFormInt = {
username: '',
password: '',
repasswd: ''
}
loginFormRef = ref<FormInstance>()
}
export interface userRegisterI {
username: string;
passwd: string
}
export interface homeSentenceI {
type: string,
count: number,
}
export interface userCenterI {
uid: number,
}5.这样axios封装基本完成了,我们在处理业务逻辑,需要发起请求时,就可以在api.ts中定义对应请求函数,在对应业务逻辑处理的地方导入api.ts调用该请求函数,处理响应结果即可。
<template>
<div class="home-box">
<div class="small_container home-container">
<div>
<SeconedNav></SeconedNav>
<TipNav />
</div>
<div class="home-right">
<LatestNew />
</div>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import TipNav from '../components/homepage/TipNav.vue'
import LatestNew from '@/components/LatestNew.vue';
import { homeSentence, homeSentenceLike } from '../utils/api'
import store from '../store'
export default defineComponent({
name: "HomePage",
components: {
TipNav,
LatestNew
},
beforeCreate() {
//发起请求,获取句子信息
homeSentence({ type: 'recommend', count: 0 }).then((res) => {
//这里处理请求响应的结果
//将数据存储到store上
store.commit('homepageOptions/checkRecommendData', res.data)
});
//发起请求,获取谁喜欢了句子
homeSentenceLike().then((res) => {
//这里处理请求响应的结果
//将数据存储到store上
store.commit('homepageOptions/checkhomeSentenceLikeData', res)
})
}
})
</script>
<style lang="scss" scoped>
.home-container {
display: flex;
}
.home-right {
margin-top: 18px;
}
</style>6.axios封装的好处
- 利于项目开发管理和规范化
- 方便配置代理方式
版权声明:本文为m0_53016870原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。