Reputation: 5782
I have a index.js
file which contains my routes and I'm trying to create a beforeEnter
guard on the admin panel route and only let authenticated admins in. The problem is that when I console.log(store.getters.isLoggedIn)
, I get this:
ƒ isLoggedIn(state) {
return state.user.token ? true : false
}
instead of true
or false
and I'm not sure why is this happening. My getter looks like this:
getters: {
isLoggedIn: state => {
return state.user.token ? true : false
}
}
and my routes are here:
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import AdminPanel from '../views/AdminPanel.vue'
import store from "../store/authentication.js";
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'home',
component: Home
},
{
path: "/admin",
component: AdminPanel,
beforeEnter: (to, from, next) => {
console.log(store.getters.isLoggedIn)
}
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
store.js
import Vue from 'vue'
import Vuex from 'vuex'
import authentication from './authentication'
import cart from './cart'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
authentication,
cart
}
})
export default store
authentication.js
const authentication = {
state: {
user: null
},
getters: {
isLoggedIn: state => {
return state.user.token ? true : false
}
}
}
export default authentication
Upvotes: 1
Views: 1774
Reputation: 63119
First import the main store instead of importing a Vuex module directly:
import store from "../store/index.js";
Your module isn't namespaced, so now you can access the getter like:
store.getters.isLoggedIn
If it was namespaced, then you would need to use namespaced module syntax like this:
store.getters['authentication/isLoggedIn']
In this syntax, the first half of the string is the module name, then a slash, then the getter name.
When you don't namespace, you run the risk of multiple modules using getters of the same name and it's not clear which module the getter is coming from.
Upvotes: 1