How to use Vue Router from Vuex state?

In my components that I used:

this.$router.push({ name: 'home', params: { id: this.searchText }});

Change route. Now I have moved the method to my Vuex actions, and of course this.$router no longer works. It doesn't matter Vue.router . So, how can I call router methods from Vuex state?

+8
vuex vue-router
source share
4 answers

I assume vuex-router-sync will not help here, since you need a router instance.

Therefore, although this does not seem ideal, you can set the instance as global in the web package, i.e.

 global.router = new VueRouter({ routes }) const app = new Vue({ router ... 

Now you can: router.push({ name: 'home', params: { id: 1234 }}) from anywhere in your application


Alternatively, if you do not like the idea of ​​the above, you can return the promise from your action. Then, if the action completed successfully, I assume that it causes a mutation or something like that, and you can resolve Promise. However, if it fails and whichever condition requires redirection, you promise to reject .

This way you can redirect routers to a component that just catches the rejected promise and starts the push router, i.e.

 # vuex actions: { foo: ({ commit }, payload) => new Promise((resolve, reject) => { if (payload.title) { commit('updateTitle', payload.title) resolve() } else { reject() } }) # component methods: { updateFoo () { this.$store.dispatch('foo', {}) .then(response => { // success }) .catch(response => { // fail this.$router.push({ name: 'home', params: { id: 1234 }}) }) 
+14
source share

I believe that rootState.router will be available in your actions if you pass router as an option to your main Vue constructor.

As GuyC mentioned, I also thought that you'd better give up the promise of your action and routing after you resolve it. In simple words: dispatch(YOUR_ACTION).then(router.push()) .

0
source share

In this situation, I use .go instead of .push .

Sorry, there is no explanation why, but in my case it worked. I leave this for future Googlers, like me.

0
source share
  state: { anyObj: {}, // Just filler _router: null // place holder for router ref }, mutations: { /*** * All stores that have this mutation will run it * * You can call this in App mount, eg... * mounted () { * let vm = this * vm.$store.commit('setRouter', vm.$router) * } * setRouter (state, routerRef) { state._router = routerRef } }, actions: { /*** * You can then use the router like this * --- someAction ({ state }) { if (state._router) { state._router.push('/somewhere_else') } else { console.log('You forgot to set the router silly') } } } } 
0
source share

All Articles