zxdfe / FE-Interview

Every step counts
34 stars 1 forks source link

第76题:Vue2中,路由守卫有哪些? #77

Open zxdfe opened 2 years ago

zxdfe commented 2 years ago

全局守卫

路由守卫

组件内守卫

完整的导航解析流程

  1. 导航被触发。
  2. 在失活的组件里调用 beforeRouteLeave 守卫。
  3. 调用全局的 beforeEach 守卫。
  4. 在重用的组件里调用 beforeRouteUpdate 守卫(2.2+)。
  5. 在路由配置里调用 beforeEnter
  6. 解析异步路由组件。
  7. 在被激活的组件里调用 beforeRouteEnter
  8. 调用全局的 beforeResolve 守卫(2.5+)。
  9. 导航被确认。
  10. 调用全局的 afterEach 钩子。
  11. 触发 DOM 更新。
  12. 调用 beforeRouteEnter 守卫中传给 next 的回调函数,创建好的组件实例会作为回调函数的参数传入。
CDwenhuohuo commented 1 year ago

Global guard:

Global Pre Guard (beforeEach): Invoked before navigation starts to check permissions and authenticate users

Global Resolution Guard (beforeResolve) : Called before navigation is confirmed, where asynchronous routing data, etc., can be processed.

Global afterEach: Called after navigation is complete and can be used for statistics, page scrolling, and other operations

Route Exclusive Guard (beforeEnter) : This parameter is defined in route configuration and written in a separate routing rule. This parameter is valid only for the current route and is used to guard the current route.

Component internal guard:

beforeRouterEnter: is the function that executes before the route switch enters the current page. It is called only before the component is activated (that is, initialized).

beforeRouterUpdate: Resends the request when changing routes dynamically.

beforeRouterLeave: This guard function is called when the user leaves the current page to save data before leaving.

Three parameters are accepted by default:

to: indicates the page route object to be jumped to

-Penny: from where

next: The function that controls the jump. Call the function next (' /xxx ') to perform the page jump. next(false) blocks

These guards are automatically triggered when the route changes. By using these guards, the data can be controlled and processed during route jump, and the necessary security authentication and user identification can be carried out. Using route guard can better protect user information security and application stability.