
// 声明全局前置导航守卫
// 只要发生了路由的跳转,一定会触发beforeEach指定的function 回调函数
router.beforeEach(function(to, from, next) {
// to: 将要访问的路由的信息对象
// from: 将要离开的路由的信息对象
// next() : 放行
next()
})

router.beforeEach(function(to, from, next) {
if(to.path === '/main') {
const token = localStorage.getItem('token')
if(token) {
// 访问的后台主页,且有token,直接放行
next()
} else {
// 访问后台主页,但是没有token,则要先登录才能访问
next('/login')
}
} else {
// 访问的不是后台主页,直接放行
next()
}
})
参考: 黑马vue视频,感谢llb老师。