vue设置全局路由守卫

2,664 阅读2分钟

讲解

当一个导航触发时,全局前置守卫按照创建顺序调用。守卫是异步解析执行,此时导航在所有守卫 resolve 完之前一直处于 等待中。

每个守卫方法接收三个参数:

to: Route: 即将要进入的目标 路由对象

from: Route: 当前导航正要离开的路由

next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。

next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。

next(false): 中断当前的导航。如果浏览器的 URL 改变了 (可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。

next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。你可以向 next 传递任意位置对象,且允许设置诸如 replace: true、name: 'home' 之类的选项以及任何用在 router-link 的 to prop 或 router.push 中的选项。

next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。

2 配置

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

在route.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