1. 定义根state:ajaxIsLoading
2. 在Axios拦截器中commit不同的状态实现状态切换
3. 组件中通过getter获取ajaxIsLoading状态

Axios 拦截器配置

import Vue from 'vue'
import Axios from 'axios'
import AppStore from '../store'
import * as types from '../store/mutation-types.js'

Vue.prototype.$http = Axios

Axios.interceptors.request.use(config => {
    // console.log('ajax begin request')
    AppStore.commit(types.AJAX_BEGIN_RQUEST)
    return config;
})

Axios.interceptors.response.use(config => {
    // console.log('ajax get response')
    AppStore.commit(types.AJAX_END_REQUEST)
    return config
})

Vuex

const state = {
    ajaxIsLoading: false
}

const mutations = {
    ['AJAX_BEGIN_REQUEST'](state) {
        state.ajaxIsLoading = true
    },
    ['AJAX_END_REQUEST'](state) {
        state.ajaxIsLoading = false
    }
}

const getter = {
    ajaxIsLoading: state => state.ajaxIsLoading
}

Loading.vue

<template>
    <div >
        <div  >
            <img src="../assets/loading.gif" alt="loading">
        </div>
    </div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
    name: 'loading',
    computed: {
        ...mapGetters(['ajaxIsLoading'])

    }
}
</script>
<style>
#loading-container {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: .3;
    background: #ccc;
    z-index: 10000;
}

#loading {
    position: absolute;
    left: 50%;
    top: 50%;
    width: 40px;
    height: 40px;
    z-index: 100001;
}
</style>

 

相关文章:

  • 2022-12-29
  • 2021-11-05
  • 2022-12-23
  • 2021-10-25
  • 2022-12-23
  • 2021-05-22
  • 2021-08-08
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-07-23
  • 2022-01-08
  • 2022-12-23
  • 2022-12-23
  • 2021-10-02
  • 2022-12-23
相关资源
相似解决方案