vue3+ts完成axios封装
1.安装依赖:命令行:引入相应的axios和vue-axioscnpm install axios vue-axios -S2.axios封装接下来我们使用class来封装,而不是传统的函数封装,因为类更具有封装性,更加灵活。2.1创建request.jsimport axios, {AxiosInstance, AxiosRequestConfig, AxiosResponse} from 'a
·
1.安装依赖:
命令行:引入相应的axios和vue-axios
cnpm install axios vue-axios -S
2.axios封装
接下来我们使用class来封装,而不是传统的函数封装,因为类更具有可塑性,更加灵活。
2.1创建request.js
import axios, {AxiosInstance, AxiosRequestConfig, AxiosResponse} from 'axios';
import {message, notification} from 'ant-design-vue';
export class Request {
public static axiosInstance: AxiosInstance;
// constructor() {
// // 创建axios实例
// this.axiosInstance = axios.create({timeout: 1000 * 12});
// // 初始化拦截器
// this.initInterceptors();
// }
public static init() {
// 创建axios实例
this.axiosInstance = axios.create({
baseURL: '/api',
timeout: 6000
});
// 初始化拦截器
this.initInterceptors();
return axios;
}
// 为了让http.ts中获取初始化好的axios实例
// public getInterceptors() {
// return this.axiosInstance;
// }
// 初始化拦截器
public static initInterceptors() {
// 设置post请求头
this.axiosInstance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
/**
* 请求拦截器
* 每次请求前,如果存在token则在请求头中携带token
*/
this.axiosInstance.interceptors.request.use(
(config: AxiosRequestConfig) => {
// const token = Vue.ls.get(ACCESS_TOKEN)
// if (token) {
// config.headers['Authorization'] = 'Bearer ' + token
// }
// 登录流程控制中,根据本地是否存在token判断用户的登录情况
// 但是即使token存在,也有可能token是过期的,所以在每次的请求头中携带token
// 后台根据携带的token判断用户的登录情况,并返回给我们对应的状态码
// if (config.headers.isJwt) {
const token = localStorage.getItem('ACCESS_TOKEN');
if (token) {
config.headers.Authorization = 'Bearer ' + token;
}
// }
return config;
},
(error: any) => {
console.log(error);
},
);
// 响应拦截器
this.axiosInstance.interceptors.response.use(
// 请求成功
(response: AxiosResponse) => {
// if (res.headers.authorization) {
// localStorage.setItem('id_token', res.headers.authorization);
// } else {
// if (res.data && res.data.token) {
// localStorage.setItem('id_token', res.data.token);
// }
// }
if (response.status === 200) {
// return Promise.resolve(response.data);
return response;
} else {
Request.errorHandle(response);
// return Promise.reject(response.data);
return response;
}
},
// 请求失败
(error: any) => {
const {response} = error;
if (response) {
// 请求已发出,但是不在2xx的范围
Request.errorHandle(response);
return Promise.reject(response.data);
} else {
// 处理断网的情况
// eg:请求超时或断网时,更新state的network状态
// network状态在app.vue中控制着一个全局的断网提示组件的显示隐藏
// 关于断网组件中的刷新重新获取数据,会在断网组件中说明
ElMessage({
message: '网络连接异常,请稍后再试!',
type: 'success',
})
}
});
}
/**
* http握手错误
* @param res 响应回调,根据不同响应进行不同操作
*/
private static errorHandle(res: any) {
// 状态码判断
switch (res.status) {
case 401:
break;
case 403:
break;
case 404:
ElMessage({
message: '请求的资源不存在',
type: 'warning',
})
break;
default:
ElMessage.error('连接错误');
}
}
}
2.2 main.ts中引入axios和request
import { createApp } from 'vue'
import App from './App.vue'
import { Request } from '@/service/request'
import VueAxios from 'vue-axios'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import router from './router'
import store from './store'
import { components } from './plugins/element-plus'
const app = createApp(App)
for (const cpn of components) {
app.component(cpn.name, cpn)
}
app.use(store)
app.use(router)
app.use(ElementPlus)
app.use(VueAxios, Request.init())
app.mount('#app')
2.3 编写接口 api.js
import { Request } from './request'
export function login (parameter: any) {
return Request.axiosInstance({
url: '/cxLogin',
method: 'post',
data: parameter
})
}
export function getUserList(parameter?: any) {
return Request.axiosInstance({
url: '/users',
method: 'get',
data: parameter
})
}
export function home(parameter?: any) {
return Request.axiosInstance({
url: '/home',
method: 'post',
data: parameter
})
}
3. vue组件中使用
<template>
<div class="login-container">
<el-form :model="loginForm" @submit="handleSubmit"><!--@submit.native.prevent-->
<el-form-item>
<el-input v-model="loginForm.account" placeholder="account" style="width: 350px" >
</el-input>
</el-form-item>
<el-form-item>
<el-input v-model="loginForm.password" type="password" placeholder="Password" style="width: 350px">
</el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="handleSubmit">
登陆
</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script lang="ts">
import '../../reset.scss'
import '../../global.css'
import { defineComponent, reactive } from "vue";
import { login } from '@/service/api'
import { useRouter } from 'vue-router'
export default defineComponent({
name: "index",
components: {
},
setup(){
const loginForm = reactive({
account: '',
password:''
})
const router = useRouter()
const handleSubmit = (e: Event)=> {
const param = {
account: loginForm.account,
password: loginForm.password
}
login(param).then(response => {
const res: any = response.data
if(res.code === 200){
localStorage.setItem('ACCESS_TOKEN', res.data);
router.push("/flow")
}
})
}
return{
loginForm,
handleSubmit
}
}
})
</script>
<style lang="scss" scoped>
</style>
更多推荐
已为社区贡献43条内容
所有评论(0)