欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

Vue-router路由判断页面未登录跳转到登录页面

程序员文章站 2022-06-12 22:27:11
...
本文主要为大家带来一篇Vue-router路由判断页面未登录跳转到登录页面的实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧,希望能帮助到大家。

如下所示:

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();
 }
});

在这之前是给路由加一个meta属性:

{
 path: '/index',
 meta: {
  title: '',
  requireAuth: true, // 添加该字段,表示进入这个路由是需要登录的
 },
}

注意:但是事实是登录的时候大多数时候并不进行跳转,所以这里需要在login跳转的路径中再加一段:

if(this.$route.query.redirect){
//  let redirect = decodeURIComponent(this.$route.query.redirect);
  let redirect = this.$route.query.redirect;
  this.$router.push(redirect);
}else{
  this.$router.push('/');
 }

相关推荐:

三种Vue-Router来实现组件间跳转

关于vue-router实现组件间的跳转参数传递

详解vue-router路由与页面间导航

以上就是Vue-router路由判断页面未登录跳转到登录页面的详细内容,更多请关注其它相关文章!