router.beforeEach((to,from,next)=>{
if(to.matched.some(res=>res.meta.isLogin)){//判断是否需要登录
if (localStorage['auth']) {
next();
}else{
next({
path:"/login",
});
}
}else{
next()
}
});
首先在定义路由的时候就需要多添加一个自定义字段isLogin:true ,用于判断该路由的访问是否需要登录。如果用户已经登录,则顺利进入路由,
否则就进入登录页面,然后在通过钩子函数beforeEach()对路由进行一个判断。