如果我将directly导航到管理员保护的路由http://127.0.0.1:8000/dashboard/,导航总是被拒绝,因为在判断路由保护时状态尚未加载.

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

我该如何避开鸡和蛋的问题?

files below truncated for relevancy

主要的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)
})

路由.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之前,从Vue创建中取出this.$store.dispatch("auth/load")个并运行它.

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({...})

})

Vue.js相关问答推荐

为什么在Vue.js中修改非react 性似乎是react 性的?

Vue Datepicker 不会在渲染时显示默认日期

Vue3如何将自定义事件绑定到路由视图中的特定组件?

如果单元格不可见,则以编程方式打开行的编辑模式. Ag 网格,Vue.js

如何在Vue js 3中根据API响应替换react 值

在 VueJS 中为 Get、Post、Patch 配置全局标头的最佳方法

Defer推迟执行,直到外部脚本加载到 Vue.js

在下拉菜单上使用箭头键滚动

当前端和后端位于虚拟 docker 网络中时,如何使用 axios 寻址后端主机

Vue:从 Vue 实例更新组件数据

Laravel 事件未广播

Javascript/vue.js 接收json

我可以修改 Vue.js VNodes 吗?

如何将 git hash 添加到 Vue.js 组件

如何在 Vue.js 插槽范围内传递方法

如何从方法内部访问数据

何时使用

使用 axios 和 vue.js 取消先前的请求

脚本npm run dev和npm run watch是做什么用的?

Vuejs 不会在 HTML 表格元素中呈现组件