1. 定義根state:ajaxIsLoading
2. 在Axios攔截器中commit不一樣的狀態實現狀態切換
3. 組件中經過getter獲取ajaxIsLoading狀態vue
Axios 攔截器配置ios
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 })
Vuexajax
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.vuevuex
<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; 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>