How to use Vue Router from Vuex state?

I a situation, I find myself to use .go instead of .push.

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


I'm assuming vuex-router-sync won't help here as you need the router instance.

Therefore although this doesn't feel ideal you could set the instance as a global within webpack, i.e.

global.router = new VueRouter({
  routes
})

const app = new Vue({
  router
  ...

now you should be able to: router.push({ name: 'home', params: { id: 1234 }}) from anywhere within your app


As an alternative if you don't like the idea of the above you could return a Promise from your action. Then if the action completes successfully I assume it calls a mutation or something and you can resolve the Promise. However if it fails and whatever condition the redirect needs is hit you reject the Promise.

This way you can move the routers redirect into a component that simply catches the rejected Promise and fires the vue-router push, 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 }})
      })