Router beforeEach guard 在 Vue created() 中加载状态之前执行

Router beforeEach guard executed before state loaded in Vue created()

如果我直接导航到管理员保护的路由,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 创建中取出 this.$store.dispatch("auth/load") 并在创建 Vue 之前 运行 它。

store.dispatch("auth/load")

router.beforeEach((to, from, next) => {...}

new Vue({...})

如果 auth/load 是异步的,那么 return 它的一个承诺,并且你的代码在回调中初始化你的 Vue。

store.dispatch("auth/load").then(() => {

  router.beforeEach((to, from, next) => {...}

  new Vue({...})

})