Accessing Vuex state when defining Vue-Router routes Accessing Vuex state when defining Vue-Router routes vue.js vue.js

Accessing Vuex state when defining Vue-Router routes


As suggested here, what you can do is to export your store from the file it is in and import it in the routes.js. It will be something like following:

You have one store.js:

import Vuex from 'vuex'//init storeconst store = new Vuex.Store({    state: {        globalError: '',        user: {            authenticated: false        }     },     mutations: {         setGlobalError (state, error) {             state.globalError = error         }     }})export default store

Now in routes.js, you can have:

import Vue from 'vue'import VueRouter from 'vue-router'import store from ./store.jsVue.use(VueRouter)//define routesconst routes = [    { path: '/home', name: 'Home', component: Home },    { path: '/login', name: 'Login', component: Login },    { path: '/secret', name: 'Secret', component: SecretPage, meta: { requiresLogin: true }]Router.beforeEach((to, from, next) => {    if (to.matched.some(record => record.meta.requiresLogin) && ???) {        // You can use store variable here to access globalError or commit mutation         next("/Login")    } else {        next()    }})

In main.js also you can import store:

import Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex)import store from './store.js'//init appconst app = new Vue({    router: Router,    store,    template: '<app></app>',    components: { App }}).$mount('#app')


You may use router.app to access the root Vue instance the router was injected into, then access store regularly via router.app.$store.

const router = new Router({    routes,})router.beforeEach((to, from, next) => {    // access store via `router.app.$store` here.    if (router.app.$store.getters('user')) next();    else next({ name: 'login' });})

Here is the API Reference.


I ended up moving the store out of main.js and into store/index.js, and importing it into the router.js file:

import store from './store'//routesconst routes = [    { path: '/home', name: 'Home', component: Home },    { path: '/login', name: 'Login', component: Login },    { path: '/secret', name: 'Secret', component: SecretPage, meta: { requiresLogin: true }]    //guard clauseRouter.beforeEach((to, from, next) => {    if (to.matched.some(record => record.meta.requiresLogin) && store.state.user.authenticated == false) {        store.commit("setGlobalError", "You need to log in before you can perform this action.")        next("/Login")    } else {        next()    }})