Home >Web Front-end >Front-end Q&A >vue-router has several hooks

vue-router has several hooks

青灯夜游
青灯夜游Original
2021-12-22 16:49:383142browse

There are 7 hooks: 1. beforeEach; 2. beforeResolve; 3. afterEach; 4. beforeEnter; 5. beforeRouteEnter; 6. beforeRouteUpdate; 7. beforeRouteLeave.

vue-router has several hooks

The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.

vue-router How many hook functions are there? What exactly is it and what is the execution process?

First start with the mind map.

vue-router 钩子函数.png

Analysis

Hook function

ofvue-router actually refers to the navigation guard .

Quote from the official website

"Navigation" indicates that the routing is changing.

vue-router The navigation guard provided is mainly used to jump or cancel Guard Navigation. There are multiple opportunities to build into the route navigation process: globally, exclusive to a single route, or at the component level.

That is: Global Guard, Routing Guard, Component Guard.

Code Demonstration Environment Construction

First briefly set up the environment

index.js

/*
 * @Description:一尾流莺
 * @Date: 2021-03-21 16:17:56
 * @LastEditTime: 2021-07-18 15:14:42
 * @FilePath: \vite-project-js\src\router\index.js
 */

import { createRouter, createWebHashHistory } from 'vue-router';

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/a',
      component: () => import('../components/A.vue'),
    },
    {
      path: '/b',
      component: () => import('../components/B.vue'),
    },
    {
      path: '/c',
      component: () => import('../components/C.vue'),
    },
  ],
});
export default router;

main .js

// index.js
import router from "./router"; 
createApp(App).use(router).mount("#app");

Page A

<template>
  <div>
    <h1>我是页面A啊</h1>
    <comp></comp>
  </div>
</template>

Page B

<template>
  <div>
    <h1>我是页面B啊</h1>
    <comp></comp>
  </div>
</template>

Page C

<template>
  <div>
    <h1>我是页面C啊</h1>
    <comp></comp>
  </div>
</template>

General components

<template>
  <div>我是公用组件啊</div>
</template>

Current page It’s like this, it’s a bit ugly, let’s just watch it, we’re not here to learn css

vue-router has several hooks

Global Guard

As the name suggests, it is defined globally, which is the router object in our index.js.

beforeEach

Global front guard, triggered before route jump, it will each time navigation trigger.

Register a global beforeEach guard through router.beforeEach.

vue-router has several hooks

Parameters

beforeEach The global front guard receives three parameters

  • to : Route: The target route object that is about to enter
  • from: Route: The route object that the current navigation is about to leave
  • next: Function: This method must be called otherwise routing will be blocked.

Note: next Parameters do not need to be added, but once added, they must be called once, otherwise routing jumps, etc. will stop.

next() Several situations of the method

  • next(): Proceed to the next hook in the pipeline.
  • next(false): Interrupt current navigation. Return to the address corresponding to the from route.
  • next('/') or next({ path: '/' }): Jump to a different address, the parameters that can be passed are the same as router.push The options are the same.
  • next(error): Navigation terminates, and the error will be passed to the router.onError() registered callback.

Let’s print out the first two parameters and take a look. They contain paths, parameters, meta-information, etc.

vue-router has several hooks

Return value

  • false: Cancel the current navigation.
  • null, undefined, true or direct return: Call the next navigation guard.

Define multiple guards

You can define multiple global front guards and call them according to the order of creation. Navigation is pending until all guards are completed.

In the following example, we define two beforeEach global pre-guards. It can be seen that the page jump occurs only after two logs are printed out two seconds later.

vue-router has several hooks

vue-router has several hooks

Except beforeEach global front guard, other global guards can be defined multiple times, and The navigation is waiting until all guards are completed, and other hook functions will not be demonstrated.

beforeResolve

Global resolution guard, before routing jump, all internal guards and are asynchronous The routing component is triggered after it is parsed, it is also triggered during each navigation .

Register a global resolution guard through router.beforeResolve.

router.beforeResolve((to, from, next) => {
  next();
})

回调参数,返回值和 beforeEach 一样。也可以定义多个全局解析守卫。

afterEach

全局后置钩子,它发生在路由跳转完成后,beforeEachbeforeResolve 之后,beforeRouteEnter(组件内守卫)之前。它同样在 每次导航 时都会触发。

通过 router.afterEach 注册一个全局后置钩子。

vue-router has several hooks

这个钩子的两个参数和 beforeEach 中的 tofrom 一样。然而和其它全局钩子不同的是,这些钩子不会接受 next 函数,也不会改变导航本身。

路由守卫

顾名思义,就是跟路由相关的钩子,我们的路由守卫只有一个,就是 beforeEnter

beforeEnter

需要在路由配置上定义 beforeEnter 守卫,此守卫只在进入路由时触发,在 beforeEach 之后紧随执行,不会在 paramsqueryhash 改变时触发。

vue-router has several hooks

beforeEnter 路由守卫的参数是 tofromnext ,同 beforeEach 一样。

组件守卫

顾名思义,是定义在路由组件内部的守卫。

beforeRouteEnter

vue-router has several hooks

路由进入组件之前调用,该钩子在全局守卫 beforeEach 和路由守卫 beforeEnter 之后,全局 beforeResolve 和全局 afterEach 之前调用。

参数包括 tofromnext

该守卫内访问不到组件的实例,也就是 thisundefined,也就是他在 beforeCreate 生命周期前触发。

beforeRouteUpdate

vue-router has several hooks

对于 beforeRouteUpdate 来说,this 已经可用了,所以给 next 传递回调就没有必要了。

beforeRouteLeave

vue-router has several hooks

对于 beforeRouteLeave 来说,this 已经可用了,所以给 next 传递回调就没有必要了。

总结

完整的导航解析流程

  • 导航被触发。

  • 在失活的组件里调用 beforeRouteLeave 守卫。

  • 调用全局的 beforeEach 守卫。

  • 在重用的组件里调用 beforeRouteUpdate 守卫。

  • 在路由配置里调用 beforeEnter

  • 解析异步路由组件。

  • 在被激活的组件里调用 beforeRouteEnter

  • 调用全局的 beforeResolve 守卫。

  • 导航被确认。

  • 调用全局的 afterEach 钩子。

  • 触发 DOM 更新。

  • 调用 beforeRouteEnter 守卫中传给 next 的回调函数,创建好的组件实例会作为回调函数的参数传入。

上面是官方给出的答案,现在我们用流程图来直观的展示一下。

vue-router has several hooks

【相关推荐:《vue.js教程》】

The above is the detailed content of vue-router has several hooks. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What does vue spa mean?Next article:What does vue spa mean?