最近做了一个需求记录下:跳转页面进行登录状态判定,没登录就返回登录页。这里用到vue的路由守卫。
官方介绍:https://router.vuejs.org/zh/guide/advanced/navigation-guards.html
to是要进去页面的路由,from是从哪个页面路由调过来的,next是个方法,next()进入页面,next('/login')进入指定的login页面。具体看官方api.
router.beforeEach((to, from, next) => {
//判断进入页面要不要登录
if (to.meta.requireAuth) {
console.log('进入requireAuth')
//判断登录状态,没登录回登录页
if (sessionStorage.getItem("login") === 'true') {
console.log('next')
next()
} else {
console.log('回到登录页')
next('/login')
}
} else {
console.log('当前页面不需要登录')
next()
}
})