1. store.js使用vuex全局控制loading显示隐藏


import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    LOADING: false
  },

  mutations: {
    showLoading(state) {
      state.LOADING = true
    },
    hideLoading(state) {
      state.LOADING = false
    }
  }
  1. 新建loading公共组件页面


<template>
  <div class="loading">
    <van-loading type="spinner" color="#1989fa" />
  </div>
</template>

<script>
  import Vue from 'vue';
  import {Loading} from 'vant';
  Vue.use(Loading);
  export default {
    name: 'LOADING',
    data() {
      return {}
    },
  }
</script>

<style lang="scss" scoped>
  .loading {
    position: fixed;
    z-index: 9999;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
  1. 在App.vue中,将loading组件挂载工程节点

挂载到App.vue中之后所有的接口请求都会加载loading组件

可以需要页面单独引用


<template>
  <div id="app">
    <Loading v-show="LOADING"></Loading>
    ......//其他代码
  </div>
</template>

<script>
  import {mapState} from 'vuex'
  import Loading from '@c/Loading.vue'
  export default {
  // ...解构,将store中的state进行映射。
  // 在template可以直接使用,不需要通过this.$store.state一个获取store中的state数据computed: {
      ...mapState(['LOADING'])
    },
    name: 'App',
    components: {Loading}
  }
</script>
  1. 请求拦截器响应拦截器配置

封装好的axios中,利用axios拦截器实现请求提交store显示loading;

请求失败或者完成提交store隐藏loading。


import Vue from "vue";
import axios from 'axios';
import store from '../../store';

// 请求拦截器
axios.interceptors.request.use(function (config) {
  store.commit('showLoading')
  return config;
}, function (error) {
  store.commit('hideLoading')
  return Promise.reject(error);
});

//响应拦截器
axios.interceptors.response.use((response) => {
  store.commit('hideLoading')
  return response.data;
}, (error) => {
  store.commit('hideLoading')
  return Promise.reject(error);
});

//绑定到vue原型中
Vue.prototype.$http = axios;
  1. 如果在单个请求中使用


// 在请求时
this.$store.commit('showLoading')

//请求完成后  
this.$store.commit('hideLoading')

原文地址:https://blog.csdn.net/m0_61663332/article/details/128610258

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_14177.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注