This time I will bring you theNavigationof VueRouter. How to use the guard. What are thePrecautionsfor using the VueRouter's navigation guard. The following is a practical case. Let's take a look. .
Mainly used to guard navigation by jumping or canceling.
For example, to determine the login information: all users who are not logged in will jump to the login page. Determine whether the necessary operation is carried out. If not, interrupt the jump.
is divided into three categories: global guard,routingguard, component guard
Global Guard
beforeEach beforeResolve afterEach
Route Guard
beforeEnter
Component Guard
beforeRouteEnter // 在渲染该组件的对应路由被 confirm 前调用 // 不!能!获取组件实例 `this` // 因为当守卫执行前,组件实例还没被创建 虽然无法直接获取组件实力 但是我们可以通过next参数的回调函数获取到当前实例进行操作 beforeRouteEnter: (to, from, next) => { next((vm) => { //vm就是当前组件实例 }); } beforeRouteUpdate // 在当前路由改变,但是该组件被复用时调用 // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候, // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。 // 可以访问组件实例 `this` beforeRouteLeave // 导航离开该组件的对应路由时调用 // 可以访问组件实例 `this`
Parameter introduction
Parameters involved in these navigation guards: to, from, next
Except for the global guard afterEach which only has to and from, the rest have three parameters
(摘抄自官网) to: Route: 即将要进入的目标 路由对象 from: Route: 当前导航正要离开的路由 next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。 next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。 next(false): 中断当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。 next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。 next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。
Operating mechanism
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
JS implements label scrolling switching
JS implements mouse following special effects
How Webpack builds Electron applications
The above is the detailed content of How to use VueRouter's navigation guard. For more information, please follow other related articles on the PHP Chinese website!