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

本文深入解析了Vue.js中全局守卫和路由独享守卫的使用方法,通过具体代码示例,展示了如何利用守卫控制路由跳转,实现权限验证等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.全局守卫

回调函数中的参数,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()
          }
      }
    },

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值