How to display a “loading” animation while a lazy-loaded route component is being loaded?

前端 未结 3 2059
不知归路
不知归路 2020-12-13 00:38

I have split my app into multiple chunks with webpack\'s code splitting feature so that the entire application bundle isn\'t downloaded when the user visits my webpage.

3条回答
  •  难免孤独
    2020-12-13 01:10

    For what it's worth, I'll share what I ended up doing for my situation.

    I'm using Vuex so it was easy to create an app-wide "loading" state which any component can access, but you can use whatever mechanism you want to share this state.

    Simplified, it works like this:

    function componentLoader(store, fn) {
      return () => {
        // (Vuex) Loading begins now
        store.commit('LOADING_BAR_TASK_BEGIN');
    
        // (Vuex) Call when loading is done
        const done = () => store.commit('LOADING_BAR_TASK_END');
    
        const promise = fn();
        promise.then(done, done);
        return promise;
      };
    }
    
    function createRoutes(store) {
      const load = fn => componentLoader(store, fn);
    
      return [
        {
          path: '/foo',
          component: load(() => import('./components/foo.vue')),
        },
        {
          path: '/bar',
          component: load(() => import('./components/bar.vue')),
        },
      ];
    }
    

    So all I have to do is wrap every () => import() by my load() function which takes care of setting the loading state. Loading is determined by observing the promise directly instead of relying on router-specific before/after hooks.

提交回复
热议问题