通常項目中,有時候會要求,你在數據請求的時候顯示一張gif圖片,而後數據加載完後,消失。這個,通常只須要在封裝的axios中寫入js事件便可。固然,咱們首先須要在app.vue中,加入此圖片。以下:vue
<template> <div id="app"> <loading v-show="fetchLoading"></loading> <router-view></router-view> </div> </template> <script> import { mapGetters } from 'vuex'; import Loading from './components/common/loading'; export default { name: 'app', data() { return { } }, computed: { ...mapGetters([ 'fetchLoading', ]), }, components: { Loading, } } </script> <style> #app{ width: 100%; height: 100%; } </style>
這裏的fetchLoading是存在vuex裏面的一個變量。在store/modules/common.js裏須要以下定義:ios
/* 此js文件用於存儲公用的vuex狀態 */ import api from './../../fetch/api' import * as types from './../types.js' const state = { // 請求數據時加載狀態loading fetchLoading: false } const getters = { // 請求數據時加載狀態 fetchLoading: state => state.fetchLoading } const actions = { // 請求數據時狀態loading FETCH_LOADING({ commit }, res) { commit(types.FETCH_LOADING, res) }, } const mutations = { // 請求數據時loading [types.FETCH_LOADING] (state, res) { state.fetchLoading = res } }
loading組件以下:vuex
<template> <div class="loading"> <img src="./../../assets/main/running.gif" alt=""> </div> </template> <script> export default { name: 'loading', data () { return {} }, } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> .loading{ position: fixed; top:0; left:0; z-index:121; width: 100%; height: 100%; background: rgba(0,0,0,0.3); display: table-cell; vertical-align: middle; text-align: center; } .loading img{ margin:5rem auto; } </style>
最後在fetch/api.js裏封裝的axios裏寫入判斷loading事件便可:以下axios
// axios的請求時間 let axiosDate = new Date() export function fetch (url, params) { return new Promise((resolve, reject) => { axios.post(url, params) .then(response => { // 關閉 loading圖片消失 let oDate = new Date() let time = oDate.getTime() - axiosDate.getTime() if (time < 500) time = 500 setTimeout(() => { store.dispatch('FETCH_LOADING', false) }, time) resolve(response.data) }) .catch((error) => { // 關閉 loading圖片消失 store.dispatch('FETCH_LOADING', false) axiosDate = new Date() reject(error) }) }) } export default { // 組件中公共頁面請求函數 commonApi (url, params) { if(stringQuery(window.location.href)) { store.dispatch('FETCH_LOADING', true); } axiosDate = new Date(); return fetch(url, params); } }