昨天在写页面的全局守卫时出现的问题,跟着别人的教程来的,结果发现他的代码不能正确执行,源代码如下:
//未能成功拦截的代码
router.beforeEach((to, from, next) => {
//问题点
if(to.meta.requireAuth){ //如果页面需要拦截
//console.log('用户信息:',store.state.user.username)
if (store.state.user.username) { //存在用户信息则不拦截
next()
} else { //否则没有登录,拦截,重定向至登录界面
next({
path: 'login',
query: {redirect: to.fullPath}
})
}
} else {
next()
}
}
)
meta{requireAuth: true}只有需要拦截的页面有,如果需要拦截则查询是否存在用户信息(即是否登录过),如果没有登录就重定向到登录页面,但实测并没有拦截页面,多次尝试修改之后发现判断条件要改为if(meta.requireAuth == true)才能正常进入代码块,解决代码:
//拦截成功的代码
router.beforeEach((to, from, next) => {
//修改判断条件后成功拦截
if(to.meta.requireAuth == true){ //如果页面需要拦截
//console.log('用户信息:',store.state.user.username)
if (store.state.user.username) { //存在用户信息则不拦截
next()
} else { //否则没有登录,拦截,重定向至登录界面
next({
path: 'login',
query: {redirect: to.fullPath}
})
}
} else {
next()
}
}
)