How to navigate using vue router from Vuex actions How to navigate using vue router from Vuex actions vue.js vue.js

How to navigate using vue router from Vuex actions


import router from './router'

and use router.push

Simple like that.


This example may help you.

main.js

import Vue from "vue";import VueRouter from "vue-router";...Vue.use(VueRouter);export const router = new VueRouter({    mode: 'hash',    base: "./",    routes: [        { path: "/", component: welcome},        { path: "/welcome", component: welcome},    ]})

actions.js

import {router} from "../main.js"export const someAction = ({commit}) => {    router.push("/welcome");} 


It looks like you aren't injecting your router into your app, hence it being 'undefined'

In previous versions of vue-router you would: Vue.use(VueRouter), with 2.0 you can inject the router into the app like below:

const routes = [  { path: '/foo', component: Foo },]const router = new VueRouter({  routes})const app = new Vue({  router // inject the router}).$mount('#app')

this should then make it available as this.$router throughout the app


Following answering a related question: How to use Vue Router from Vuex state? it seems that Vuex won't receive the router instance at this.$router. Therefore two methods were suggested to provide access to the router instance.

The first is more direct which involves setting a webpack global to the instance.

The second involves using Promises with your vuex action that would allow your components to utilise their reference to the router instance following the actions Promise resolving / rejecting.