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 id="loading-container" v-show="ajaxIsLoading"> <div id="loading" > <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; 100%; height: 100%; opacity: .3; background: #ccc; z-index: 10000; } #loading { position: absolute; left: 50%; top: 50%; 40px; height: 40px; z-index: 100001; } </style>