Adrian Latorre
Adrian Latorre

Reputation: 161

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()

Thanks a lot!

Upvotes: 9

Views: 3981

Answers (3)

Thomas Urban
Thomas Urban

Reputation: 5061

As of now (mid 2018) API of Vuex supports subscriptions. Using them it is possible to be notified when a mutation is changing your store and to adjust the router on demand.

The following example is an excerpt placed in created() life-cycle hook of a Vue component. It is subscribing to mutations of store waiting for the first match of desired criteria to cancel subscriptions and adjust route.

{
  ...
  created: function() {
    const unsubscribe = this.$store.subscribe( ( mutation, state ) => {
      if ( mutation.type === "name-of-your-mutation" && state.yourInfo === desiredValue ) {
        unsubscribe();
        this.$router.push( { name: "name-of-your-new-route" } );
      }
    } );
  },
  ...
}

Upvotes: 0

Haluk Keskin
Haluk Keskin

Reputation: 11

Put an event listener on your app.vue file then emit en event by your mutation function. But I suggest you wrapping the action in a promise is good way

App.vue:

import EventBus from './eventBus';

 methods: {   
    redirectURL(path) {
      this.$router.go(path)}
    },

 created() {
  EventBus.$on('redirect', this.redirectURL)
 }

mutation:

import EventBus from './eventBus';

LOGIN_SUCCESSFUL() {
  state.blabla = "blabla";
  EventBus.$emit('redirect', '/dashboard')

}

Upvotes: 0

DerJacques
DerJacques

Reputation: 332

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.

Upvotes: 3

Related Questions