【发布时间】: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