定义Vue-Router路由时访问Vuex状态

JavaScript

TonyEva

2020-03-12

我有以下Vuex商店(main.js):

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

//init store
const store = new Vuex.Store({
    state: {
        globalError: '',
        user: {
            authenticated: false
        }
     },
     mutations: {
         setGlobalError (state, error) {
             state.globalError = error
         }
     }
})

//init app
const app = new Vue({
    router: Router,
    store,
    template: '<app></app>',
    components: { App }
}).$mount('#app')

我还为Vue-Router(routes.js)定义了以下路由:

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

//define routes
const routes = [
    { path: '/home', name: 'Home', component: Home },
    { path: '/login', name: 'Login', component: Login },
    { path: '/secret', name: 'Secret', component: SecretPage, meta: { requiresLogin: true }
]

我试图这样做,以便如果Vuex商店的user对象具有authenticated属性false,则让路由器将用户重定向到“登录”页面。

我有这个:

Router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.requiresLogin) && ???) {
        // set Vuex state's globalError, then redirect
        next("/Login")
    } else {
        next()
    }
})

问题是我不知道如何user从beforeEach函数内部访问Vuex存储的对象。

我知道我可以在组件内部使用路由器保护逻辑BeforeRouteEnter,但这会使每个组件混乱。我想在路由器级别集中定义它。

第1016篇《定义Vue-Router路由时访问Vuex状态》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
JinJin宝儿 2020.03.12

这就是我想要的。

在App.vue中,我将对存储身份验证详细信息的cookie保持监视。(显然,在身份验证之后,我会将包含身份验证详细信息的令牌存储为cookie)

现在,只要此Cookie变空,我都会将用户路由到/ login页面。注销将删除cookie。现在,如果用户注销后回击,则由于cookie不存在(这要求用户登录),因此该用户将被路由到登录页面。

十万个冷笑话 2020.03.12

与其他应用程序状态分开管理位置状态会使这样的事情变得比原本需要的困难。在处理完Redux和Vuex中的类似问题之后,我开始使用模块管理Vuex商店内的位置状态router您可能要考虑使用这种方法。

在您的特定情况下,您可以在Vuex商店本身内部监视位置何时更改,并分派适当的“重定向”操作,如下所示:

dispatch("router/push", {path: "/login"})

将位置状态作为Vuex模块进行管理比您想象的要容易。如果您想尝试一下,可以使用我的作为起点:

https://github.com/geekytime/vuex-router

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android