Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

javascript - How to access a Vuex getter from Vue router

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
question from:https://stackoverflow.com/questions/65843993/how-to-access-a-vuex-getter-from-vue-router

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...