目标:
1.登陆用户不能再次回到login
2.没有登陆就不能访问除login之外的其他页面
方案:
const whiteList = ['/reg', '/login'] // 白名单
router.beforeEach((to, from, next) => {
// 取出token(vuex)
const token = store.state.user.token
console.log('全局前置路由守卫', token)
if (token) {
// 去登录页
if (to.path === '/login') {
console.log('你已经登录了,就不能去login,转到主页')
next('/')
} else {
next()
}
} else {
// 没有登录,只能去白名单(那些不需要token就可以访问的页面)
if (whiteList.includes(to.path)) {
next()
} else {
console.log('你没有登录,转到登录页')
next('/login')
}
// next() // 重点强调next一定要调用
}
})