How can I call Vuex store getters in routes.js file
-
I’m building a project using the quasar framework, I have created it using Quasar CLI.
I’m facing a problem with Vuex getter, I don’t know how can call it inside the routes.js file.
I have this code in my routes.js:import store from 'src/store/accounts' const routes = [ { path: "/", component: () => import("pages/Home.vue"), beforeEnter: (to, from, next) => { if (store.getters.isAuthenticated) { console.log('authenticated user'); next('timeline') } else next() } }, ... ]
It looks like the getter not called because I have a
console.log
in my getter and I don’t get it in the console.// getters.js export function isAuthenticated (state) { console.log(state, 'from getters'); return !!state.token }
This is the
index.js
file of the accounts moduleimport state from './state' import * as getters from './getters' import * as mutations from './mutations' import * as actions from './actions' export default { namespaced: true, state, getters, mutations, actions }
and this is the
index.js
file of the store folder that contains the modulesimport Vue from 'vue' import Vuex from 'vuex' import example from './module-example' import accounts from './accounts' Vue.use(Vuex) export default function (/* { ssrContext } */) { const Store = new Vuex.Store({ modules: { accounts, example, }, // enable strict mode (adds overhead!) // for dev mode only strict: process.env.DEBUGGING }) return Store }
Does any help, please?
-
@oussama-he make your router/routes.js a function that accepts a store parameter from your router/index.js. example:
// src/router/routes.js ... const routes = (store) => [ ... beforeEnter: (to, from, next) => { if (store.getters.isAuthenticated) { console.log('authenticated user'); next('timeline') } else next() } ... ] export default (store) => routes (store) // src/router/index.js import routes from './routes.js' export default function ({ store }) { // <-- accepts store as parameter const Router = new VueRouter({ scrollBehavior: () => ({ x: 0, y: 0 }), routes: routes(store), // <--- pass the store context to your routes.js ...