简体   繁体   English

Vue:在路由保护(路由 beforeEach)中访问商店道具/变量?

[英]Vue : Accessing store prop/variable in route guard (route beforeEach)?

I'm struggling to do a check against a store variable/property in the route beforeEach guard.. I cannot seem to figure out how to access the store's properties..我正在努力在每个警卫之前检查路线中的商店变量/属性。我似乎无法弄清楚如何访问商店的属性。

My code :我的代码:

import Vue from 'vue'
import Router from 'vue-router'
import store from "@/components/store.js"
... other imports..

Vue.use(Router);

const routes = [
    { path: '/', component: NluEditor },
    { path: '/nlueditor', component: NluEditor },
    { path: '/login', component: Login },
    { path: '/logout', component: Logout}
];

const router = new Router({
    routes
});

router.beforeEach((to, from, next) => {
    if(to.path != '/login') {
        console.log(store)
        if (store.state.loggedInUser) {  // cannot seem to access store ? 
            console.log("You are logged in :) Go to requested page ")
            next()
        }
        else {
            console.log("Not logged in.. redirecting....")
            next('login');
        }
    }
  })

const app = new Vue({
    el: '#app',
    router,
    store,

    render: h => h(App)
})

You can access the store.您可以访问商店。 There is no problem with that as you are importing it.导入时没有问题。

The problem is with how you are accessing state.loggedInUser .问题在于您如何访问state.loggedInUser You might be using modules in your store and loggedInUser might belong to a module.您可能在商店中使用模块,而loggedInUser可能属于某个模块。 So to access it you need to refer to the module name that loggedInUser belongs to like this:所以要访问它,你需要像这样引用loggedInUser所属的模块名称:

if (store.state.moduleName.loggedInUser) {
  ? console.log("You are logged in :) Go to requested page ") 
    next() 
}

Replace moduleName with the name of the module loggedInUser belongs to.moduleName替换为loggedInUser所属模块的名称。

I was able to achieve this in a recent app by changing store.state.loggedInUser for store.getters.loggedInUser .我能够在最近的应用程序中通过将store.state.loggedInUser更改为store.getters.loggedInUser来实现这store.getters.loggedInUser

Essentially telling it to call the getter method directly instead of a mapping to the method through the state.本质上告诉它直接调用 getter 方法,而不是通过状态映射到该方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM