vue设置全局路由守卫

 

1,讲解

router.beforeEach路由跳转之前 

vue设置全局路由守卫_第1张图片

router.beforeEach((to, from, next) => {
  console.log(to);//进入的页面(下一个页面)
  console.log(from);//离开之前的页面(上一个页面)
  console.log(next);//to
  next();//这个必须要先执行一遍next()方法,而且不能带参数,带参数会陷入死循环
  //判断登录,是否带token
  if (!to.meta.requireAuth) {
    next();
  } else if (localStorage.getItem("token")) {
    next();
  } else {
    next({
      path: "/Login",
      query: {
        redirect: to.fullPath
      }
    });
  }
});

2,配置

在router.js文件:

const router=  new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [{
    path: '/',
    name: 'home',
    component: Home,  
    meta:{
      requiresAuth:true,// 是否需要登录
      keepAlive: true // 是否缓存组件
    }, 
    redirect: {
      name: 'Login'
    } 
  },
  {
    path: '/HomePage', // 首页面
    name: 'HomePage',
    component: () => import('./views/HomePage.vue'),
    redirect: {
      name: 'onlineQuery'
    } ,
    meta: {                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
      title: "首页面",
      requiresAuth:true ,
      keepAlive: true  
    }

},
 {
    path: '*', // 未匹配到路由时重定向
    redirect: '/',
    meta: {
        // auth: true,
        // keepAlive: true
    }
}
]
})


//全局路由守卫
router.beforeEach((to,from,next) => {
  if(to.meta.requiresAuth){
     // console.log(to.name)
       if(sessionStorage.getItem("token")){
         next()
       }else{
        //  next({name:'Login',query:{redirect:to.name}})
        next({
                  path: "/Login",
                  query: {
                      redirect: to.fullPath
                  }
              });
       }
   }else{
     // console.log(to.name)
     next()
   }
 })
 
 export default router

 

你可能感兴趣的:(vue)