优化Vue页面切换加载

1,263 阅读1分钟

当用户网络较慢时,异步加载组件需要一定时间,此时显示加载中动画相对比较友好。 可以通过 vue-router 和 vuex 轻松实现:

import Vue from 'vue'; import Vuex from 'vuex';
const store = new Vuex.Store({
  state: {
    isLoading: false
  },
  mutations: {
    updateLoadingStatus (state, isLoading) {
      state.isLoading = isLoading;
    }
  }
});
const app = new Vue({
  store,
  router,
  render: v => v(App)
}).$mount('#app');

其次通过 vue-router 的 beforeEach 和 afterEach 更改 isLoading 状态:

router.beforeEach((route, redirect, next) => {    
    /* 显示加载中动画 */  
    store.commit('updateLoadingStatus', true);  
    next();
});
router.afterEach(route => {  
    /* 隐藏加载中动画 */ 
    store.commit('updateLoadingStatus', false);
    
});

最后在 App.vue 里通过 isLoading 显示/隐藏加载中动画即可:

<template>
  <div style="height: 100%;">
    <div v-show="isLoading">加载中</div><!-- 可以添加自己更加友好的加载动画 -- >
        <router-view v-show="!isLoading"></router-view>
    </div>
</template>
  <script type="text/babel">
    export default {
        computed: {
            isLoading() {
                 return this.$store.state.isLoading
            }
        }
    }
  </script>