Categories
Vue Answers

How to access Vuex state when defining Vue Router routes?

Spread the love

Sometimes, we want to access Vuex state when defining Vue Router routes.

In this article, we’ll look at how to access Vuex state when defining Vue Router routes.

How to access Vuex state when defining Vue Router routes?

To access Vuex state when defining Vue Router routes, we can import the store in the file with the Vue Router hooks.

For instance, we write

import Vuex from "vuex";

const store = new Vuex.Store({
  state: {
    globalError: "",
  },
  mutations: {
    setGlobalError(state, error) {
      state.globalError = error;
    },
  },
});

export default store;

to create a store and export it using the Vuex.Store constructor in store.js.

Then in router.js, we write

import Vue from "vue";
import VueRouter from "vue-router";
import store from "./store.js";

Vue.use(VueRouter);

const routes = [
  { path: "/home", name: "Home", component: Home },
  { path: "/login", name: "Login", component: Login },
  {
    path: "/secret",
    name: "Secret",
    component: SecretPage,
    meta: { requiresLogin: true },
  },
];

const router = new VueRouter({
  routes,
});

router.beforeEach((to, from, next) => {
  if (store.state.globalError) {
    //...
    next("/Login");
  } else {
    next();
  }
});

to add the routes array with the routes.

And then we create a VueRouter instance with the routes.

Next, we get the globalError store state from store.state.globalError in the beforeEach callback.

Conclusion

To access Vuex state when defining Vue Router routes, we can import the store in the file with the Vue Router hooks.

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 *