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

pym*_*rco 7 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)
})
Run Code Online (Sandbox Code Playgroud)

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",
            },
        },
    ],
})
Run Code Online (Sandbox Code Playgroud)

Ber*_*ert 12

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

store.dispatch("auth/load")

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

new Vue({...})
Run Code Online (Sandbox Code Playgroud)

如果auth/load是异步的,那么从它返回一个promise并执行你的代码在回调中初始化你的Vue.

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

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

  new Vue({...})

})
Run Code Online (Sandbox Code Playgroud)

  • 那就做到了!谢谢伯特! (2认同)