【问题标题】:Router beforeEach guard executed before state loaded in Vue created()Router beforeEach 守卫在 Vue created() 中加载状态之前执行
【发布时间】:2017-12-30 14:17:03
【问题描述】:

如果我直接导航到管理员保护的路由http://127.0.0.1:8000/dashboard/,导航总是被拒绝,因为在检查路由器保护时状态尚未加载。

beforeEach 在 Vue created 之前执行,因此无法识别当前登录的用户。

我该如何解决这个先有鸡还是先有蛋的问题?

以下文件因相关性而被截断

main.js

router.beforeEach((to, from, next) => {
    //
    // This is executed before the Vue created() method, and thus store getter always fails initially for admin guarded routes
    //

    // The following getter checks if the state's current role is allowed
    const allowed = store.getters[`acl/${to.meta.guard}`]

    if (!allowed) {
        return next(to.meta.fail)
    }

    next()
})

const app = new Vue({
    router,
    store,

    el: "#app",

    created() {
        // state loaded from localStorage if available
        this.$store.dispatch("auth/load")
    },

    render: h => h(App)
})

router.js

export default new VueRouter({
    mode: 'history',

    routes: [
        {
            path: '/',
            name: 'home',
            component: () => import('../components/Home.vue'),
            meta: {
                guard: "isAny",
            },
        },

        {
            path: '/dashboard/',
            name: 'dashboard',
            component: () => import('../components/Dashboard.vue'),
            meta: {
                guard: "isAdmin",
            },
        },
    ],
})

【问题讨论】:

    标签: vue.js vue-router vuex


    【解决方案1】:

    this.$store.dispatch("auth/load")从Vue创建中取出,并在创建Vue之前运行它。

    store.dispatch("auth/load")
    
    router.beforeEach((to, from, next) => {...}
    
    new Vue({...})
    

    如果auth/load 是异步的,则从它返回一个promise,并让你的代码在回调中初始化你的Vue。

    store.dispatch("auth/load").then(() => {
    
      router.beforeEach((to, from, next) => {...}
    
      new Vue({...})
    
    })
    

    【讨论】:

    • 做到了!谢谢伯特!
    • @JeffS 这将如何工作?这不会导致 OP 试图解决的问题吗?
    猜你喜欢
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    相关资源
    最近更新 更多