vuejs / vuex-router-sync

Effortlessly keep vue-router and vuex store in sync.
MIT License
2.52k stars 125 forks source link

Automatic dispatch upon route change #87

Closed eirikb closed 5 years ago

eirikb commented 5 years ago

I'm not sure how to call store.dispatch when a route changes. mounted lifecycle won't work, since component isn't re-mounted on route param change (/user/1, /user/2).

What I do today is something like:

const router = new VueRouter({
  routes: [
    {
      path: '/', component: App, meta: {dispatch: 'loadData'}
    }
  ]
});

router.beforeEach((to, from, next) => {
  const {dispatch} = to.meta;
  if (dispatch) store.dispatch(dispatch);
  next();
});

I'm not sure if this is the most elegant/correct solution, but it does seem to work, and I find myself re-using this pattern for almost every app.
Would this be a good addition to this library (if it is a good solution)?

posva commented 5 years ago

Well, it's indeed a pattern that can be used in some apps. Personally, I prefer calling the dispatch in the View component so I can handle the loading state locally but some prefer handling the loading state before reaching the view like you do. You can even have some loading bar going on if you wait for the dispatch to be over before calling next