当前位置:   article > 正文

vue全局loading实现_vue 全局loading

vue 全局loading

目录

一、思路:

1、主要逻辑

2、优化

3、所需知识

二、具体实施:

1、store

2、请求拦截器

3、响应拦截器

4、使用loading组件


一、思路:

1、主要逻辑

利用vue中的仓库(vue2可用vuex,vue3可用pinia,本例为vue2),创建一个全局可访问参数isLoading,当请求时,isLoading为true,结束时为false。

2、优化

思路来自于引用计数圾回收机制,可增加新全局参数loadingResCount,每次请求开始时,通过拦截器使loadingResCount数加一,结束时loadingResCount数减一,当loadingResCount为0时,isLoading为false。

3、所需知识

vuex、request拦截器,elementui中loading组件

二、具体实施:

1、store

新建loading.js文件(和其他store放在同一目录下),此文件用来存放loading显示隐藏逻辑

vuex使用请参考官网:开始 | Vuex

  1. const state = {
  2. isLoading: false,
  3. loadingResCount: 0,
  4. };
  5. const mutations = {
  6. startLoading(state) {
  7. if (state.loadingResCount === 0) {
  8. state.isLoading = true;
  9. }
  10. state.loadingResCount++;
  11. },
  12. endLoading(state) {
  13. if (state.loadingResCount <= 0) return;
  14. state.loadingResCount--;
  15. if (state.loadingResCount === 0) {
  16. state.isLoading = false;
  17. }
  18. },
  19. };
  20. const actions = {
  21. startLoading(context) {
  22. context.commit("startLoading");
  23. },
  24. endLoading({ commit }) {
  25. commit("endLoading");
  26. },
  27. };
  28. export default {
  29. state,
  30. mutations,
  31. actions,
  32. };

2、请求拦截器

每次请求调用startLoading方法,当请求发生错误时,调用endLoading方法

此处做了个小优化,当下拉框是通过api请求数据时,不触发全局loading,具体实现是判断headers中的loading参数,如果为false,则不进入全局loading计数器

  1. // request拦截器
  2. service.interceptors.request.use(
  3. (config) => {
  4. // 下拉联动筛选不需要loading
  5. if (config.headers.loading !== false) {
  6. store.dispatch("startLoading");
  7. }
  8. return config;
  9. },
  10. (error) => {
  11. dispatch.dispatch("endLoading");
  12. console.log(error);
  13. Promise.reject(error);
  14. }
  15. );
  1. export function selectApi(data) {
  2. return request({
  3. url: 'api',
  4. method: 'get',
  5. params: data,
  6. headers: {
  7. loading: false,
  8. },
  9. });
  10. }

3、响应拦截器

每次响应调用endLoading,使loadingResCount减一,这里注意使用了try,catch代码块,最后都会走finally,所以只在finally中调用endLoading

  1. // 响应拦截器
  2. service.interceptors.response.use(
  3. (res) => {
  4. try {
  5. return res.data;
  6. } catch {
  7. console.log("响应拦截器异常");
  8. } finally {
  9. store.dispatch("endLoading");
  10. }
  11. },
  12. (error) => {
  13. store.dispatch("endLoading");
  14. return Promise.reject(error);
  15. }
  16. );

4、使用loading组件

最后在全局loading组件中,将变量绑定到v-loading

  1. <div class="main-container" v-loading="$store.state.loading.isLoading" element-loading-text="加载中...">
  2. </div>

好啦,完结撒花,如果对你有帮助请不要吝啬点赞和收藏哦~

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/218865
推荐阅读
相关标签
  

闽ICP备14008679号