Vue3使用axios请求拦截器和vuex设置全局loading

        在开发中使用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的拦截器里面去修改。

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue3中使用TypeScript结合Pinia来实现全局loading的方式如下: 首先,我们需要安装vue-router、pinia和axios,可以使用以下命令进行安装: ``` npm install vue-router@next pinia axios ``` 接下来我们创建一个store模块来管理全局loading状态。在src/store目录下创建一个名为loading.ts的文件,代码如下: ```typescript import { store } from 'pinia'; export const useLoadingStore = store('loading'); export const loadingStore = useLoadingStore({ state: () => ({ isLoading: false, }), actions: { setLoading(loading: boolean) { this.isLoading = loading; }, }, }); ``` 然后在src/main.ts文件中注册pinia和创建一个全局loading插件,代码如下: ```typescript import { createApp } from 'vue'; import { createPinia } from 'pinia'; import App from './App.vue'; import router from './router'; import axios from 'axios'; import { loadingStore } from './store/loading'; const app = createApp(App); const pinia = createPinia(); app.use(pinia); // 创建全局loading插件 app.config.globalProperties.$loading = { show() { loadingStore.setLoading(true); }, hide() { loadingStore.setLoading(false); }, }; // axios拦截器 axios.interceptors.request.use(function (config) { loadingStore.setLoading(true); return config; }, function (error) { return Promise.reject(error); }); axios.interceptors.response.use(function (response) { loadingStore.setLoading(false); return response; }, function (error) { loadingStore.setLoading(false); return Promise.reject(error); }); app.use(router); app.mount('#app'); ``` 最后,在需要使用loading的地方,可以通过以下方式来调用全局loading状态: ```typescript import { defineComponent } from 'vue'; import { loadingStore } from './store/loading'; export default defineComponent({ methods: { fetchData() { loadingStore.setLoading(true); // 发起异步请求 // ... loadingStore.setLoading(false); }, }, }); ``` 以上就是使用Vue3和TypeScript结合Pinia实现全局loading的方法。我们首先在store模块中定义了一个loading状态,并提供了相应的方法来控制loading的显示和隐藏。然后在main.ts中创建了全局loading插件,并通过axios拦截器来控制loading的显示和隐藏。最后,在需要使用loading的地方调用相应的方法即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值