Vue 路由 导航守卫(全局守卫、路由独享守卫)

一.全局守卫

回调函数中的参数,to:进入到哪个路由去,from:从哪个路由离开,next:函数,决定是否展示你要看到的路由页面。main.js中设置全局守卫

router.beforeEach((to, from, next) => {
  let isLogin = localStorage.getItem('isLogin')
  if (to.matched.length === 0) { //没有匹配到当前路由
    next('/error')
  } else if (!isLogin && to.path !== '/login') {
    //如果没有登录,跳转到登录页面
    next('/login')
  } else {
    if ((to.path === '/login' || to.path === '/error') && isLogin) {
      //如果已经登录,却尝试访问登录页面或者错误页面,将继续保持原本的页面
       next('check')
    } else {
      next()
    }
    // next()
  }
  // next()
})

二.路由独享的守卫

beforeEnter:(to,from,next)=>{},用法与全局守卫一致。只是,将其写进其中一个路由对象中,只在这个路由下起作用。

  {
      path: '/login',
      name: 'login',
      component: Login,
      beforeEnter(to,from,next){
        console.log(to)
          let isLogin = localStorage.getItem('isLogin')
          if (to.matched.length === 0) { //没有匹配到当前路由
            next('/error')
          } else if (!isLogin && to.path !== '/login') {
            //如果没有登录,跳转到登录页面
            next('/login')
          } else {
            if ((to.path === '/login' || to.path === '/error') && isLogin) {
              //如果已经登录,却尝试访问登录页面或者错误页面,将继续保持原本的页面
               next('/check')
            } else {
              next()
            }
            // next()
          }
      }
    },

 

你可能感兴趣的:(vue)