Categories
Vue Answers

How to navigate using Vue Router from Vuex actions?

Spread the love

Sometimes, we want to navigate using Vue Router from Vuex actions.

In this article, we’ll look at how to navigate using Vue Router from Vuex actions.

How to navigate using Vue Router from Vuex actions?

To navigate using Vue Router from Vuex actions, to import the router into our Vuex store and call push on it.

For instance, we write

main.js

import Vue from "vue";
import VueRouter from "vue-router";

//...

Vue.use(VueRouter);

export const router = new VueRouter({
  base: "/",
  routes: [
    { path: "/", component: welcome },
    { path: "/welcome", component: welcome },
  ],
});

to create a router object and export it.

Then we write

import { router } from "./main.js";

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

to import the router and then call router.push in our Vuex action method.

Conclusion

To navigate using Vue Router from Vuex actions, to import the router into our Vuex store and call push on it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *