我正在构建 SPA,问题是检查用户是否是管理员。
在 Vue.auth.getUserInfo()
之后,我想停止整个应用程序并等待 API 响应,Vue.auth.user.isAdmin
始终为 false,因为我不没有来自 api 的响应...
这是 router.beforeEach
router.beforeEach((to, from, next) => {
if(Vue.auth.user.authenticated == false) {
Vue.auth.getUserInfo();
}
if(Vue.auth.user.isAdmin) {
next({ name: 'admin.index' })
} else {
next({name: 'client.index'})
}
}
获取用户信息方法:
getUserInfo() {
Vue.http.get('/api/me')
.then(({data}) => {
this.user = data;
}, () => {
this.logout();
})
}
最佳答案
假设 Vue.auth.user.isAdmin
的状态在您的 Vue.auth.getUserInfo()
逻辑中进行管理,您可以尝试 Promise 方法(未经测试) :
getUserInfo() {
return new Promise((resolve, reject) => {
Vue.http.get('/api/me')
.then(({data}) => {
this.user = data;
// Or, to use when consuming this within the then() method:
resolve(data);
}, () => {
reject();
})
})
}
然后,当你在你的守卫中消耗它时( https://router.vuejs.org/en/advanced/navigation-guards.html ):
// A couple small auth/guard helper functions
function guardCheck(next) {
if(Vue.auth.user.isAdmin) {
next({ name: 'admin.index' })
} else {
next({name: 'client.index'})
}
}
function guardLogout(next) {
Vue.auth.user.logout()
.then(() => {
next({ name: 'home.index', params: { logout: success }})
})
}
router.beforeEach((to, from, next) => {
if(Vue.auth.user.authenticated === false && !to.matched.some(record => record.meta.isGuest)) {
Vue.auth.getUserInfo()
.then((user) => {
guardCheck(next)
})
.catch(() => {
// Not sure how your logout logic works but maybe...
guardLogout(next)
})
} else {
guardCheck(next)
}
}
关于javascript - VueRouter等待ajax完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41489750/