路由跳转,判断是否登录

router.beforeEach((to, from, next) => {
// 路由过滤,判断是否登录
当需要在某些页面进行判断是否登录时可以写在路由元中进行判断,如果项目必备必须登录才可以看,可已直接进行判断,无需写在路由元中
if (to.matched.some(record => record.meta.requireAuth)) {
if (localStorage.loginstatus.get()) {
next()
} else {
next({
path: ‘/login’,
query: { redirect: to.fullPath }
})
}
} else {
next()
}
})
第二种方式
{ path: ‘/repository’,
name: ‘repository’,
meta: {
requireAuth: true, // 添加该字段,表示进入这个路由是需要登录的
},
component: Repository
},

router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requireAuth)){ // 判断该路由是否需要登录权限
if (token) { // 判断当前的token是否存在
next();
}
else {
next({
path: ‘/login’,
query: {redirect: to.fullPath} // 将跳转的路由path作为参数,登录成功后跳转到该路由
})
}
}
else {
next();
}
});
vue-router路由跳转判断用户是否存在
router.beforeEach((to, from, next) => {
//console.log(“to:”, (to));
//console.log(“from:”, (from));
//console.log(“next:”, (next));
if(to.path == ‘/login’) {
window.sessionStorage.removeItem(‘access-user’);
next();
} else {
let user = JSON.parse(window.sessionStorage.getItem(‘access-user’));
var toUrl = to.path;
console.log(“jump to login. toUrl:”, (toUrl));
if(!user) {
next({
path: ‘/login’,
query: { url: toUrl }
});
} else {
next();
}
next();
}
});

猜你喜欢

转载自blog.csdn.net/weixin_43831302/article/details/89329843
今日推荐