路由器之前在Vue中加载状态之前执行的每个守卫创建()

时间:2017-07-24 21:03:29

标签: vue.js vue-router vuex

如果我将直接导航到管理员保护路由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",
            },
        },
    ],
})

1 个答案:

答案 0 :(得分:7)

从Vue创建中取出this.$store.dispatch("auth/load")并在创建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({...})

})