6

在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
    }
  }

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>

在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 {
    computed: {
      ...mapState(['LOADING'])
    },
    name: 'App',
    components: {Loading}
  }
</script>

在封装好的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;

如果在单个请求中使用

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

一斤代码
33 声望1 粉丝