Vue3使用axios请求拦截器和vuex设置全局loading方式
作者:莉是我的yo
在开发中使用loading加载动画是常见的功能。页面加载需要时间,网络不好时也需要时间,加载的过程中页面就会出现白屏的状况,如果没有使用loading来和用户进行交互,用户并不知道应用到底是出现什么问题,就会十分的影响用户体验。废话不多说,直接开始。
App.vue
既然是全局loading,那就让它在全局范围内都生效,我们在根组件内设置加载动画(可以设置css动画,js动画,Vue动画,我这里为了省事,直接使用的gif动图)。设置完调整一下css,让它出现在页面正中央。
我们通过“flage”的值,来控制loading的显示与隐藏,因为使用过程中会经常触发,所以使用v-show合适些。要做到每一次请求都能触发,就要监听“flage”的值,通过“compued”获取vuex内flage的值(使用计算属性,因为它有缓存),再通过“watch”监听值的变化,实时给flage重新赋值。如何让每次请求和响应都改变flage的值,继续往下看。
<template>
<div>
<div class="box" v-show="flage">
<img src="./assets/loading.gif" alt="">
</div>
<router-view />
</div>
</template>
<script>
import store from './store/index'
import { ref } from 'vue'
export default {
name: 'App',
setup() {
let flage = ref(false)
return {
flage,
}
},
computed: {
newData() {
return store.state.loading
}
},
watch: {
newData(newVal) {
this.flage = newVal
}
}
}
</script>
<style scoped>
.box {
width: 100%;
height: 100%;
background-color: rgba(243, 243, 243, 0.3);
position: absolute;
z-index: 9999
}
img {
width: 200px;
height: 200px;
position: absolute;
left: 50%;
top: 30%;
}
</style>
封装axios拦截器
axios拦截器包括请求拦截和响应拦截,对每一次的请求和响应都会做出处理,那我们就可以在这里通过vuex来改变“flage”的值,发请求时值为“true”,响应时值为“false”。
import axios from "axios";
import store from '../store'
// 创建axios实例
const service = axios.create({
baseURL: "/api",
timeout: 10000,
});
// 请求拦截器
service.interceptors.request.use(
(config) => {
store.commit('setLoading',true)
return config;
},
(error) => {
// 对请求错误做些什么
return Promise.reject(error);
}
);
// 响应拦截器
service.interceptors.response.use(
(response) => {
// 对响应数据做点什么
store.commit('setLoading',false) let res = response.data;
return res;
},
(error) => {
// 对响应错误做点什么:统一进行响应错误的处理
console.dir(error);
return Promise.reject(error);
}
);
export const request = service;
vuex
vuex中state的值是不能直接修改的,简单来说state是允许异步操作的,这样的话就会出现多个地方异步调用时,有的还没执行完而state里面的值就被修改了,这样程序就会报错。mutations的作用就是阻止异步调用。需要异步调用时要通过actions里面的方法去调用mutations里面的方法。扯多了,继续看我们的代码。
import { createStore } from 'vuex'
export default createStore({
state: {
loading: false,
},
getters: {},
mutations: {
setLoading(state, flage){
state.loading = flage
}
},
actions: {},
modules: {},
plugins: []
})
总结
总体来说设置全局loading不算难,就是通过axios的拦截器在每次请求或响应后修改loading的显示与隐藏。
我这里用的是vuex,其实也可以通过使用localStorage或sessionStorage来缓存flage的值,共同点就是都要在axios的拦截器里面去修改。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
