router.beforeEach((to, from, next) => {
var params = to.meta
to['query']['refresh'] = true
if (!params['check']) {
next()
} else {
Vue.http.get('check_auth?auth=' + params['auth']).then(response => {
let data = response.data
if (data['res']) {
next()
} else {
//死循环啦
Vue.prototype.$message({
message: '没有权限!',
type: 'error'
})
next('/index')
}
})
}
})
调用 next()方法才能进入下一个路由,否则的如果写了beforeEach方法,但是没有调用next()方法的话,页面会空白。默认不写 router.beforeEach((to, from, next) => {}) 的话,它是默认跳转到指定页面去的,当然如果有这个方法的话,会覆盖默认的方法。因此如果写了调用了该方法的话,切记记得调用 next() 方法。next('/') 或者 next({ path: '/' })会跳转到一个不同的地址,当前的导航会被中段,进入 path新的导航。
代码中所示的部分。当用户没有权限的时候,跳转到index,但是先会执行router.beforeEach()该方法,在index又是没有权限的,所以会死循环。
修改后的方法:
router.beforeEach((to, from, next) => {
var params = to.meta
to['query']['refresh'] = true
if (!params['check']) {
console.log(12122)
next()
} else {
Vue.http.get('check_auth?auth=' + params['auth']).then(response => {
alert(1222)
let data = response.data
if (data['res']) {
next()
} else {
Vue.prototype.$message({
message: '没有权限!',
type: 'error'
})
if (to.path === '/index') {
next()
} else {
next('/index')
}
}
})
}
})
网友评论