一般項目中,有時候會要求,你在數(shù)據(jù)請求的時候顯示一張gif圖片,然后數(shù)據(jù)加載完后,消失。這個,一般只需要在封裝的axios中寫入js事件即可。當(dāng)然,我們首先需要在app.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里需要如下定義:
/* 此js文件用于存儲公用的vuex狀態(tài) */ import api from './../../fetch/api' import * as types from './../types.js' const state = { // 請求數(shù)據(jù)時加載狀態(tài)loading fetchLoading: false } const getters = { // 請求數(shù)據(jù)時加載狀態(tài) fetchLoading: state => state.fetchLoading } const actions = { // 請求數(shù)據(jù)時狀態(tài)loading FETCH_LOADING({ commit }, res) { commit(types.FETCH_LOADING, res) }, } const mutations = { // 請求數(shù)據(jù)時loading [types.FETCH_LOADING] (state, res) { state.fetchLoading = res } }
loading組件如下:
<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里寫入判斷l(xiāng)oading事件即可:如下
// axios的請求時間 let axiosDate = new Date() export function fetch (url, params) { return new Promise((resolve, reject) => { axios.post(url, params) .then(response => { // 關(guān)閉 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) => { // 關(guān)閉 loading圖片消失 store.dispatch('FETCH_LOADING', false) axiosDate = new Date() reject(error) }) }) } export default { // 組件中公共頁面請求函數(shù) commonApi (url, params) { if(stringQuery(window.location.href)) { store.dispatch('FETCH_LOADING', true); } axiosDate = new Date(); return fetch(url, params); } }
這樣就實現(xiàn)了,項目中當(dāng)加載數(shù)據(jù)的時候,顯示gif圖片,當(dāng)數(shù)據(jù)加載出來時消失。
關(guān)于vue.js的學(xué)習(xí)教程,請大家點擊專題vue.js組件學(xué)習(xí)教程、Vue.js前端組件學(xué)習(xí)教程進行學(xué)習(xí)。
更多vue學(xué)習(xí)教程請閱讀專題《vue實戰(zhàn)教程》
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com