在 Vue created() 中加载状态之前执行的路由器 beforeEach [英] Router beforeEach guard executed before state loaded in Vue created()
问题描述
如果我直接导航到管理员保护的路线,http://127.0.0.1:8000/dashboard/
,导航总是被拒绝,因为状态没有在检查路由器防护时尚未加载.
If I navigate directly to an admin guarded route, http://127.0.0.1:8000/dashboard/
, the navigation is always rejected because the state hasn't yet loaded at the time the router guard is checked.
beforeEach
在 Vue created
之前被执行,因此当前登录的用户不被识别.
beforeEach
is being executed before Vue created
and thus the currently logged in user isn't recognized.
我该如何解决这个先有鸡还是先有蛋的问题?
How do I get around this chicken and egg issue?
以下文件因相关性而被截断
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 被创建之前运行它已创建.
Take this.$store.dispatch("auth/load")
out of the Vue creation and run it before the Vue is created.
store.dispatch("auth/load")
router.beforeEach((to, from, next) => {...}
new Vue({...})
如果 auth/load
是异步的,那么从它返回一个 promise,并在回调中用你的代码初始化你的 Vue.
If auth/load
is asynchronous, then return a promise from it and do your code initialize your Vue in the callback.
store.dispatch("auth/load").then(() => {
router.beforeEach((to, from, next) => {...}
new Vue({...})
})
这篇关于在 Vue created() 中加载状态之前执行的路由器 beforeEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!