Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vue-router中如何保护指定路由的安全? #79

Open
GGXXMM opened this issue Jan 3, 2021 · 0 comments
Open

vue-router中如何保护指定路由的安全? #79

GGXXMM opened this issue Jan 3, 2021 · 0 comments
Labels

Comments

@GGXXMM
Copy link
Owner

GGXXMM commented Jan 3, 2021

一、vue-router中路由保护策略

vue-router中保护路由安全通常使用导航守卫来做,通过设置路由导航钩子函数的方式添加守卫函数,在里面判断用户登录状态和权限,从而达到保护指定路由的目的。

二、vue-router有哪几种导航守卫(分为3类)

全局守卫 beforeEach

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
  // ...
})

路由独享守卫 beforeEnter

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      meta: {requireLogin: true},
      beforeEnter: (to, from, next) => {
        // 判断是否登录,路由独享守卫
        
      }
    }
  ]
})

组件内守卫 beforeRouteEnter

export default {
  // 在渲染组件的对应路由被confirm前调用(在导航确认前调用)
  // 不能获取组件实例`this`(当守卫执行前,组件实例还没被创建)
  beforeRouteEnter(to, from, next) {
    next(vm => {
    // 通过 `vm` 访问组件实例
    })
  },
  // 在当前路由改变,但是该组件被复用时调用
  beforeRouteUpdate(to, from, next) {},
  // 导航离开该组件的对应路由时调用
  beforeRouteLeave(to, from, next) {}
}

全局守卫、路由独享守卫、组件内守卫的区别

  • 作用范围
  • 组件实例的获取

三、导航守卫钩子函数的参数使用

  • to :即将要进入的目标路由对象
  • from :当前正要离开的路由
  • next:一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。可传递以下4种参数:
    • next()
    • next(false)
    • next('/')next({path: '/'})
    • next(error)

四、导航守卫是如何保护路由的

导航钩子函数之所以能够生效,和vue-router工作方式有关,从源码看,比如beforeEach只是注册一个hook,当路由发生变化,router准备导航之前会批量执行这些hooks。

完整的导航解析流程

  1. 导航被触发
  2. 在失活的组件里调用beforeRouteLeave守卫
  3. 调用全局的beforeEach守卫
  4. 在重复的组件里调用beforeRouteUpdate守卫
  5. 在路由配置里调用beforeEnter守卫
  6. 解析异步路由组件
  7. 在激活的组件里调用beforeRouteEnter守卫
  8. 调用全局的解析守卫beforeResolve
  9. 导航被确认
  10. 调用全局的afterEach后置钩子
  11. 触发DOM更新
  12. 调用beforeRouteEnter守卫中传给next的回调函数,创建好的组件实例会作为回调函数的参数传入
@GGXXMM GGXXMM added the vue label Dec 6, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant