[Vuejs]-Vue Router resolve view change only when all components in view have fetched their required data

1👍

There is no way to trigger component mounted hook or even to set its state without mounting it. Also, you cannot mount the next route component, while keeping rendered the previous route component.

My suggestion is to connect a centralised store to each child component (You can connect to it also independently only passing the store identifier). This way you can populate the store before mounting the component and then connect to it afterwards.

Now, you only need a way to tell the router guard which store to populate before navigating to a specific route. I suggest to set this information in route metadata, for example create an array of vuex namespaces on which a specific action should be triggered.

router.beforeEach(async (to, from, next) => {
  if (to.meta && to.meta.childStores) {
    // setting a loading flag in a global vuex module to trigger the loader
    store.commit("setLoading", true);
    // Dispatching the actions in each vuex module required for this route 
    for (let s of to.meta.childStores) {
      await store.dispatch(`${s}/fetchData`);
    }
    // disabling the loader after all requests have finished and proceeding to the next route
    store.commit("setLoading", false);
    next();
  }
  store.commit("setLoading", false);
  next();
});

You can view this Codesandbox with a minimal working example.

Leave a comment