第一步:路由拦截
首先在定义路由的时候就需要多添加一个自定义字段requireAuth,用于判断该路由的访问是否需要登录。如果用户已经登录,则顺利进入路由,
否则就进入登录页面。在路由管理页面添加meta字段
const routes = [
{
name:"登录",
path:"/login",
meta:{
requireAuth:false
}
},
{
name:'个人中心',
path:"/mine",
meta:{
requireAuth:true
}
}
]
随后在用router.beforeEach去添加条件语句,来决定是否跳转
router.beforeEach((to, from, next) => {
if(to.meta.requireAuth) {
if(store.state.token) {
next()
} else {
next({
path:'/login',
query:{redirect:to.fullPath}
})
}
}
})
然后在登录之后,在登录的方法里面修改token的状态即可