Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to change the route (VueRouter) after a mutation (Vuex)

I've searched a lot, but there is no clear answer to that. Basically, what should be the best practice to automatically change a route after a mutation?

Ex: I click a button to login() -> action login that makes an http call -> mutation LOGIN_SUCCESSFUL -> I want to redirect the user to the main page $router.go()

  • Should I wrap the action in a Promise, and then listen to the result to call the route change from the component?

  • Should I do it directly from the $store?

  • Does vuex-router-sync helps in any way?

Thanks a lot!

like image 717
Adrian Latorre Avatar asked Jan 26 '17 18:01

Adrian Latorre


1 Answers

The answer to this questions seems to be somewhat unclear in the Vue community.

Most people (including me) would say that the store mutation should not have any effects besides actually mutating the store. Hence, doing the route change directly in the $store should be avoided.

I have very much enjoyed going with your first suggestion: Wrapping the action in a promise, and changing the route from withing your component as soon as the promise resolves.

A third solution is to use watch in your component, in order to change the route as soon as your LOGGED_IN_USER state (or whatever you call it) has changed. While this approach allows you to keep your actions and mutations 100% clean, I found it to become messy very, very quickly.

As a result, I would suggest going the promise route.

like image 69
DerJacques Avatar answered Sep 20 '22 20:09

DerJacques