Vue 中 keep-alive 组件与 router-view 组件的那点事

最近项目中有小伙伴找到我,问我“为啥他写的页面第一次进去可以触发 onCreate 函数,第二次再进的时候就不触发了呢?”(因为我们项目是一个大型的项目,每个开发可能只接触到自己开发的一小部分),然后我就说你可以试着在 activated 钩子函数中做处理,然后他又接着问我“activated 钩子函数又是怎么调用的呢?”,ok!这小子是问上瘾了,我们下面就来详细解析一下。

keep-alive

<keep-alive> 包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。和 <transition> 相似,<keep-alive> 是一个抽象组件:它自身不会渲染一个 DOM 元素,也不会出现在组件的父组件链中。

当组件在 <keep-alive> 内被切换,它的 activateddeactivated 这两个生命周期钩子函数将会被对应执行。

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

主要用于保留组件状态或避免重新渲染。

为了更好的来解析 <keep-alive>,我们 copy 到一份源码(vue@^2.6.10),vue/src/core/components/keep-alive.js

/* @flow */

import {
    isRegExp, remove } from 'shared/util'
import {
    getFirstComponentChild } from 'core/vdom/helpers/index'

type VNodeCache = {
    [key: string]: ?VNode };

function getComponentName (opts: ?VNodeComponentOptions): ?string {
   
  return opts && (opts.Ctor.options.name || opts.tag)
}

function matches (pattern: string | RegExp | Array<string>, name: string): boolean {
   
  if (Array.isArray(pattern)) {
   
    return pattern.indexOf(name) > -1
  } else if (typeof pattern === 'string') {
   
    return pattern.split(',').indexOf(name) > -1
  } else if (isRegExp(pattern)) {
   
    return pattern.test(name)
  }
  /* istanbul ignore next */
  return false
}

function pruneCache (keepAliveInstance: any, filter: Function) {
   
  const {
    cache, keys, _vnode } = keepAliveInstance
  for (const key in cache) {
   
    const cachedNode: ?VNode = cache[key]
    if (cachedNode) {
   
      const name: ?string = getComponentName(cachedNode.componentOptions)
      if (name && !filter(name)) {
   
        pruneCacheEntry(cache, key, keys, _vnode)
      }
    }
  }
}

function pruneCacheEntry (
  cache: VNodeCache,
  key: string,
  keys: Array<string>,
  current?: VNode
) {
   
  const cached = cache[key]
  if (cached && (!current || cached.tag !== current.tag)) {
   
    cached.componentInstance.$destroy()
  }
  cache[key] = null
  remove(keys, key)
}

const patternTypes: Array<Function> = [String, RegExp, Array]

export default {
   
  name: 'keep-alive',
  abstract: true,

  props: {
   
    include: patternTypes,
    exclude: patternTypes,
    max: [String, Number]
  },

  created () {
   
    this.cache = Object.create(null)
    this.keys = []
  },

  destroyed () {
   
    for (const key in this.cache) {
   
      pruneCacheEntry(this.cache, key, this.keys)
    }
  },

  mounted () {
   
    this.$watch('include', val => {
   
      pruneCache(this, name => matches(val, name))
    })
    this.$watch('exclude', val => {
   
      pruneCache(this, name => !matches(val, name))
    })
  },

  render () {
   
    const slot = this.$slots.default
    const vnode: VNode = getFirstComponentChild(slot) // 获取第一个子节点
    const componentOptions: ?VNodeComponentOptions = vnode && vnode.componentOptions
    if (componentOptions) {
   
      // check pattern
      const name: ?string = getComponentName(componentOptions) // 获取节点的名称
      const {
    include, exclude } = this
      if (
        // not included
        (include && (!name || !matches(include, name))) ||
        // excluded
        (exclude && name && matches(exclude, name)) // 不在范围内的节点将不会被缓存
      ) {
   
        return vnode
      }

      const {
    cache, keys } = this
      const key: ?string = vnode.key == null
        // same constructor may get registered as different local components
        // so cid alone is not enough (#3269)
        ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${
     componentOptions.tag}` : '')
        : vnode.key // 获取缓存的 key 值
      if (cache[key]) {
    // 如果有缓存就使用缓存
        vnode.componentInstance = cache[key].componentInstance
        // make current key freshest
        remove(keys, key)
        keys.push(key)
      } else {
    // 没有缓存就将当前节点加入到缓存
        cache[key] = vnode
        keys.push(key)
        // prune oldest entry
        if (this.max && keys.length > parseInt(this.max)) {
    // 如果缓存超过最大限制将不再缓存
          pruneCacheEntry(cache, keys[0], keys, 
  • 8
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值