【发布时间】:2021-07-04 07:33:58
【问题描述】:
我有一个 django-rest-axios-vuejs 应用程序堆栈,我正在尝试在 vue-router 中做一些事情。
在vue-routerbeforeEach 守卫中,我正在验证权限,这是通过检查 vuex 商店中名为 me 的对象中的内容来完成的。一切正常,除非我刷新页面。
确实刷新页面也会清除 vuex 存储,我的 beforeEach 尝试检查存储中的 me 对象,该对象是空的。
因此,如果该 me 对象不在商店中,我想从 API 中获取它。
问题是它需要“一些时间”并且hasPermission() 方法在 API 调用完成之前执行。
所以我尝试在我的 API 调用之前放置一个 await 关键字,但它不起作用。
我的
beforeEach后卫:
router.beforeEach(async (to, from, next) => {
const isLoggedIn = getIsLoggedIn()
handleLoggedInStatus(isLoggedIn)
if (to.meta.requiresAuth) {
if (isLoggedIn) {
if (to.meta.permission) {
if (!store.state.me) await store.dispatch('FETCH_ME')
hasPermission(to.meta.permission) ? next() : next({ name: 'HomePage' })
} else {
next()
}
} else {
next({ name: 'LoginForm' })
}
} else {
next()
}
})
我在商店的行动:
actions: {
FETCH_ME: (state) => {
http
.get('base/users/me/')
.then(response => {
state.me = response.data
})
.catch(error => {
console.log(error)
})
}
}
我发现让它等待的唯一方法是执行以下操作:
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
router.beforeEach(async (to, from, next) => {
const isLoggedIn = getIsLoggedIn()
handleLoggedInStatus(isLoggedIn)
if (to.meta.requiresAuth) {
if (isLoggedIn) {
if (to.meta.permission) {
if (!store.state.me) {
store.dispatch('FETCH_ME')
await sleep(2000)
}
hasPermission(to.meta.permission) ? next() : next({ name: 'HomePage' })
} else {
next()
}
} else {
next({ name: 'LoginForm' })
}
} else {
next()
}
})
使用一点sleep() 方法让它等待“随机”(2 秒)时间。
我对@987654335@ await 的用法有点陌生,所以.. 要使await store.dispatch('FETCH_ME') 工作,我缺少什么?
提前致谢:)
【问题讨论】:
标签: javascript vue.js asynchronous vuex vue-router