We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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中保护路由安全通常使用导航守卫来做,通过设置路由导航钩子函数的方式添加守卫函数,在里面判断用户登录状态和权限,从而达到保护指定路由的目的。
const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { // ... })
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, meta: {requireLogin: true}, beforeEnter: (to, from, next) => { // 判断是否登录,路由独享守卫 } } ] })
export default { // 在渲染组件的对应路由被confirm前调用(在导航确认前调用) // 不能获取组件实例`this`(当守卫执行前,组件实例还没被创建) beforeRouteEnter(to, from, next) { next(vm => { // 通过 `vm` 访问组件实例 }) }, // 在当前路由改变,但是该组件被复用时调用 beforeRouteUpdate(to, from, next) {}, // 导航离开该组件的对应路由时调用 beforeRouteLeave(to, from, next) {} }
to
from
next
next()
next(false)
next('/')
next({path: '/'})
next(error)
导航钩子函数之所以能够生效,和vue-router工作方式有关,从源码看,比如beforeEach只是注册一个hook,当路由发生变化,router准备导航之前会批量执行这些hooks。
beforeRouteLeave
beforeEach
beforeRouteUpdate
beforeEnter
beforeRouteEnter
beforeResolve
afterEach
The text was updated successfully, but these errors were encountered:
No branches or pull requests
一、vue-router中路由保护策略
vue-router中保护路由安全通常使用导航守卫来做,通过设置路由导航钩子函数的方式添加守卫函数,在里面判断用户登录状态和权限,从而达到保护指定路由的目的。
二、vue-router有哪几种导航守卫(分为3类)
全局守卫 beforeEach
路由独享守卫 beforeEnter
组件内守卫 beforeRouteEnter
全局守卫、路由独享守卫、组件内守卫的区别
三、导航守卫钩子函数的参数使用
to
:即将要进入的目标路由对象from
:当前正要离开的路由next
:一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。可传递以下4种参数:next()
next(false)
next('/')
或next({path: '/'})
next(error)
四、导航守卫是如何保护路由的
导航钩子函数之所以能够生效,和vue-router工作方式有关,从源码看,比如beforeEach只是注册一个hook,当路由发生变化,router准备导航之前会批量执行这些hooks。
完整的导航解析流程
beforeRouteLeave
守卫beforeEach
守卫beforeRouteUpdate
守卫beforeEnter
守卫beforeRouteEnter
守卫beforeResolve
afterEach
后置钩子beforeRouteEnter
守卫中传给next
的回调函数,创建好的组件实例会作为回调函数的参数传入The text was updated successfully, but these errors were encountered: