Home > Web Front-end > JS Tutorial > body text

A detailed introduction to hook functions in Vue

不言
Release: 2018-07-23 10:46:11
Original
2453 people have browsed it

The content shared with you in this article is about Vue’s hook functions [route navigation guard, keep-alive, life cycle hook]. It has certain reference value. Friends in need can refer to it.

Preface

When it comes to Vue’s hook functions, many people may only stick to some very simple and commonly used hooks (created,mounted). Moreover, I have not studied the differences carefully, and when to use which hook. Moreover, Vue’s life cycle is also a relatively frequent test point in interviews. So how to answer such questions will make people confused. It feels bright...

Vue-Router Navigation Guard:

Sometimes, we need to perform some operations through routing, such as the most common login permission verification. When the user meets the conditions , let them enter the navigation, otherwise cancel the jump and jump to the login page to let them log in.

For this reason, we have many ways to embed the routing navigation process: Global, exclusive to a single route, or component-level, it is recommended to read the routing document first

Global guard

vue-router has three guards globally:

  1. router.beforeEach global front guard before entering the route

  2. router.beforeResolve Global parsing guard (2.5.0) Called after beforeRouteEnter is called

  3. router.afterEach After the global post hook enters the route

Usage method:

    // main.js 入口文件
    import router from './router'; // 引入路由
    router.beforeEach((to, from, next) => { 
      next();
    });
    router.beforeResolve((to, from, next) => {
      next();
    });
    router.afterEach((to, from) => {
      console.log('afterEach 全局后置钩子');
    });
Copy after login

to, from, next These three parameters:

to and from are routing objects that will enter and leave, the routing object refers to the routing object usually obtained through this.$route.

next:Function This parameter is a function, and must be called, otherwise the route cannot be entered (the page is blank).

  • next() Enter the route.

  • next(false): Cancel the entry route and reset the url address to the from routing address (that is, the routing address to be left).

  • next jumps to a new route, the current navigation is interrupted, and a new navigation is started again.

    We can jump like this: next('path address') or next({path:''}) or next({name:''})
    and allow settings such as replace: true, Options like name: 'home'
    and the object options you use in router-link or router.push.

Route Exclusive Guard

If you don’t want to configure guards globally, you can configure guards separately for certain routes:

    const router = new VueRouter({
      routes: [
        {
          path: '/foo',
          component: Foo,
          beforeEnter: (to, from, next) => { 
            // 参数用法什么的都一样,调用顺序在全局前置守卫后面,所以不会被全局守卫覆盖
            // ...
          }
        }
      ]
    })
Copy after login

In the routing component Guard:

  1. beforeRouteEnter Before entering the route

  2. beforeRouteUpdate (2.2) When the route reuses the same component

  3. beforeRouteLeave When leaving the current route

Introduction in the document:

  beforeRouteEnter (to, from, next) {
    // 在路由独享守卫后调用 不!能!获取组件实例 `this`,组件实例还没被创建
  },
  beforeRouteUpdate (to, from, next) {
    // 在当前路由改变,但是该组件被复用时调用 可以访问组件实例 `this`
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
  },
  beforeRouteLeave (to, from, next) {
    // 导航离开该组件的对应路由时调用,可以访问组件实例 `this`
  }
Copy after login

beforeRouteEnter access this

Because the hook is called before the component instance is created, the component instance this cannot be obtained. You can access the component instance by passing a callback to next
.

But the execution timing of the callback is after mounted, so in my opinion the access to this here is not very meaningful, it can be placed in created or mounted inside.

    beforeRouteEnter (to, from, next) {
    console.log('在路由独享守卫后调用');
      next(vm => {
        // 通过 `vm` 访问组件实例`this` 执行回调的时机在mounted后面,
      })
    }
Copy after login

beforeRouteLeave:

Called when the navigation leaves the corresponding route of this component. We use it to prevent the user from leaving, such as before saving the draft, or before the user leaves. , destroy setInterval to prevent the timer from still being called after leaving.

    beforeRouteLeave (to, from , next) {
      if (文章保存) {
        next(); // 允许离开或者可以跳到别的路由 上面讲过了
      } else {
        next(false); // 取消离开
      }
    }
Copy after login

Some knowledge about hooks:

Error catching of routing hook functions

If we have in the hook function of global guard/route exclusive guard/component route guard Errors can be captured like this:

    router.onError(callback => { 
    // 2.4.0新增 并不常用,了解一下就可以了 
      console.log(callback, 'callback');
    });
Copy after login

There are more instance methods in the routing document: dynamically adding routes, etc. If you are interested, you can learn about it.

Jump to an infinite loop, the page is always blank

I understand that many people will encounter this problem, take a look at this pseudo code:

    router.beforeEach((to, from, next) => {
      if(登录){
         next()
      }else{
          next({ name: 'login' }); 
      }
    });
Copy after login

Look at the logic It seems to be correct, but when we jump to login, because we are still not logged in at this time, we will keep jumping to login and then loop endlessly, and the page will always be blank. , so: we need to change the judgment conditions slightly.

    if(登录 || to.name === 'login'){ next() } // 登录,或者将要前往login页面的时候,就允许进入路由
Copy after login

Jump of global post hook:

The document mentions that because router.afterEach does not accept the next function, it will not change the navigation itself, which means that only It can be used as a hook, but when I tried it, I found that we can achieve the jump in this form:

    // main.js 入口文件
    import router from './router'; // 引入路由
    router.afterEach((to, from) => {
      if (未登录 && to.name !== 'login') {
        router.push({ name: 'login' }); // 跳转login
      }
    });
Copy after login

Well, it can also be achieved and better through router.beforeEach, so I just Show off.

Complete route navigation resolution process (excluding other life cycles):

  1. Trigger entry to other routes.

  2. Call the component guard to leave the routebeforeRouteLeave

  3. Call the pre-guard: beforeEach

  4. Call in the reused componentbeforeRouteUpdate

  5. Call the route exclusive guardbeforeEnter .

  6. 解析异步路由组件。

  7. 在将要进入的路由组件中调用beforeRouteEnter

  8. 调用全局解析守卫 beforeResolve

  9. 导航被确认。

  10. 调用全局后置钩子的 afterEach 钩子。

  11. 触发DOM更新(mounted)。

  12. 执行beforeRouteEnter 守卫中传给 next 的回调函数

你不知道的keep-alive[我猜你不知道]

在开发Vue项目的时候,大部分组件是没必要多次渲染的,所以Vue提供了一个内置组件keep-alive缓存组件内部状态,避免重新渲染,文档在这里。

文档:和 <transition> 相似,<keep-alive> 是一个抽象组件:它自身不会渲染一个 DOM 元素,也不会出现在父组件链中。

用法:

缓存动态组件:

<keep-alive> 包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们,此种方式并无太大的实用意义。

    <!-- 基本 -->
    <keep-alive>
      <component :is="view"></component>
    </keep-alive>
    
    <!-- 多个条件判断的子组件 -->
    <keep-alive>
      <comp-a v-if="a > 1"></comp-a>
      <comp-b v-else></comp-b>
    </keep-alive>
Copy after login

缓存路由组件:

使用keep-alive可以将所有路径匹配到的路由组件都缓存起来,包括路由组件里面的组件,keep-alive大多数使用场景就是这种。

    <keep-alive>
        <router-view></router-view>
    </keeo-alive>
Copy after login

生命周期钩子:

这篇既然是Vue钩子函数的专场,那肯定要扣题呀~

在被keep-alive包含的组件/路由中,会多出两个生命周期的钩子:activateddeactivated

文档:在 2.2.0 及其更高版本中,activated 和 deactivated 将会在 <keep-alive> 树内的所有嵌套组件中触发。

activated在组件第一次渲染时会被调用,之后在每次缓存组件被激活时调用

activated调用时机:

第一次进入缓存路由/组件,在mounted后面,beforeRouteEnter守卫传给 next 的回调函数之前调用:

    beforeMount=> 如果你是从别的路由/组件进来(组件销毁destroyed/或离开缓存deactivated)=>
    mounted=> activated 进入缓存组件 => 执行 beforeRouteEnter回调
Copy after login

因为组件被缓存了,再次进入缓存路由/组件时,不会触发这些钩子

    // beforeCreate created beforeMount mounted 都不会触发。
Copy after login

所以之后的调用时机是:

    组件销毁destroyed/或离开缓存deactivated => activated 进入当前缓存组件 
    => 执行 beforeRouteEnter回调
    // 组件缓存或销毁,嵌套组件的销毁和缓存也在这里触发
Copy after login

deactivated:组件被停用(离开路由)时调用

使用了keep-alive就不会调用beforeDestroy(组件销毁前钩子)和destroyed(组件销毁),因为组件没被销毁,被缓存起来了

这个钩子可以看作beforeDestroy的替代,如果你缓存了组件,要在组件销毁的的时候做一些事情,你可以放在这个钩子里。

如果你离开了路由,会依次触发:

    组件内的离开当前路由钩子beforeRouteLeave =>  路由前置守卫 beforeEach =>
    全局后置钩子afterEach => deactivated 离开缓存组件 => activated 进入缓存组件(如果你进入的也是缓存路由)
    // 如果离开的组件没有缓存的话 beforeDestroy会替换deactivated 
    // 如果进入的路由也没有缓存的话  全局后置钩子afterEach=>销毁 destroyed=> beforeCreate等
Copy after login

那么,如果我只是想缓存其中几个路由/组件,那该怎么做?

缓存你想缓存的路由:

Vue2.1.0之前:

想实现类似的操作,你可以:

  1. 配置一下路由元信息

  2. 创建两个keep-alive标签

  3. 使用v-if通过路由元信息判断缓存哪些路由。

    <keep-alive>

        <router-view v-if="$route.meta.keepAlive">
            <!--这里是会被缓存的路由-->
        </router-view>
    </keep-alive>       
    <router-view v-if="!$route.meta.keepAlive">
        <!--因为用的是v-if 所以下面还要创建一个未缓存的路由视图出口-->
    </router-view>
    //router配置
    new Router({
      routes: [
        {
          path: '/',
          name: 'home',
          component: Home,
          meta: {
            keepAlive: true // 需要被缓存
          }
        },
        {
          path: '/:id',
          name: 'edit',
          component: Edit,
          meta: {
            keepAlive: false // 不需要被缓存
          }
        }
      ]
    });
    Copy after login

Vue2.1.0版本之后:

使用路由元信息的方式,要多创建一个router-view标签,并且每个路由都要配置一个元信息,是可以实现我们想要的效果,但是过于繁琐了点。

幸运的是在Vue2.1.0之后,Vue新增了两个属性配合keep-alive来有条件地缓存 路由/组件。

新增属性:

  • include:匹配的 路由/组件 会被缓存

  • exclude:匹配的 路由/组件 不会被缓存

includeexclude支持三种方式来有条件的缓存路由:采用逗号分隔的字符串形式,正则形式,数组形式。

正则和数组形式,必须采用v-bind形式来使用。

缓存组件的使用方式

    <!-- 逗号分隔字符串 -->
    <keep-alive include="a,b">
      <component :is="view"></component>
    </keep-alive>
    
    <!-- 正则表达式 (使用 `v-bind`) -->
    <keep-alive :include="/a|b/">
      <component :is="view"></component>
    </keep-alive>
    
    <!-- 数组 (使用 `v-bind`) -->
    <keep-alive :include="[&#39;a&#39;, &#39;b&#39;]">
      <component :is="view"></component>
    </keep-alive>
Copy after login

但更多场景中,我们会使用keep-alive来缓存路由

<keep-alive include=&#39;a&#39;>
    <router-view></router-view>
</keeo-alive>
Copy after login

匹配规则:

  1. 首先匹配组件的name选项,如果name选项不可用。

  2. 则匹配它的局部注册名称。 (父组件 components 选项的键值)

  3. 匿名组件,不可匹配

比如路由组件没有name选项,并且没有注册的组件名。

  1. 只能匹配当前被包裹的组件,不能匹配更下面嵌套的子组件

比如用在路由上,只能匹配路由组件的name选项,不能匹配路由组件里面的嵌套组件的name选项。

  1. 文档:<keep-alive> 不会在函数式组件中正常工作,因为它们没有缓存实例。

  2. exclude的优先级大于include

也就是说:当includeexclude同时存在时,exclude生效,include不生效。

  <keep-alive include="a,b" exclude="a">
    <!--只有a不被缓存-->
    <router-view></router-view>
  </keep-alive>
Copy after login

当组件被exclude匹配,该组件将不会被缓存,不会调用activateddeactivated


组件生命周期钩子:

关于组件的生命周期,是时候放出这张图片了:


这张图片已经讲得很清楚了,很多人这部分也很清楚了,大部分生命周期并不会用到,这里提一下几点:

  1. ajax请求最好放在created里面,因为此时已经可以访问this了,请求到数据就可以直接放在data里面。

    这里也碰到过几次,面试官问:ajax请求应该放在哪个生命周期。

  2. 关于dom的操作要放在mounted里面,在mounted前面访问dom会是undefined

  3. 每次进入/离开组件都要做一些事情,用什么钩子:

  • 不缓存:

    进入的时候可以用createdmounted钩子,离开的时候用beforeDestorydestroyed钩子,beforeDestory可以访问thisdestroyed不可以访问this

  • 缓存了组件:

    缓存了组件之后,再次进入组件不会触发beforeCreatecreatedbeforeMountmounted如果你想每次进入组件都做一些事情的话,你可以放在activated进入缓存组件的钩子中

    同理:离开缓存组件的时候,beforeDestroydestroyed并不会触发,可以使用deactivated离开缓存组件的钩子来代替。

触发钩子的完整顺序:

将路由导航、keep-alive、和组件生命周期钩子结合起来的,触发顺序,假设是从a组件离开,第一次进入b组件:

  1. beforeRouteLeave:路由组件的组件离开路由前钩子,可取消路由离开。

  2. beforeEach: 路由全局前置守卫,可用于登录验证、全局路由loading等。

  3. beforeEnter: 路由独享守卫

  4. beforeRouteEnter: 路由组件的组件进入路由前钩子。

  5. beforeResolve:路由全局解析守卫

  6. afterEach:路由全局后置钩子

  7. beforeCreate:组件生命周期,不能访问this

  8. created:组件生命周期,可以访问this,不能访问dom。

  9. beforeMount:组件生命周期

  10. deactivated: 离开缓存组件a,或者触发a的beforeDestroydestroyed组件销毁钩子。

  11. mounted:访问/操作dom。

  12. activated:进入缓存组件,进入a的嵌套子组件(如果有的话)。

  13. 执行beforeRouteEnter回调函数next。

结语

Vue提供了很多钩子,但很多钩子我们几乎不会用到,只有清楚这些钩子函数的触发顺序以及背后的一些限制等,这样我们才能够正确的使用这些钩子,希望看了本文的同学,能对这些钩子有更加清晰的认识,使用起来更加得心应手。

相关推荐:

AngularJs中model、Controller(控制器)和View(视图)之间有什么样的关系?(图文)

Vue自定义指令及指令定义函数的具体分析(代码)

The above is the detailed content of A detailed introduction to hook functions in Vue. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template