Twlig / issuesBlog

MIT License
3 stars 0 forks source link

keep-alive及其原理 #83

Open Twlig opened 2 years ago

Twlig commented 2 years ago

keep-alive

是什么?

怎么用?

keep-alive接收三个参数:

includeexclude,传数组情况居多

动态组件

<keep-alive :include="allowList" :exclude="noAllowList" :max="amount"> 
    <component :is="currentComponent"></component> 
</keep-alive>

路由组件

<keep-alive :include="allowList" :exclude="noAllowList" :max="amount">
    <router-view></router-view>
</keep-alive>

源码

组件基础

前面说了,keep-alive是一个Vue全局组件,他接收三个参数:

顺便说说keep-alive在各个生命周期里都做了啥吧:

之前说了,keep-alive不会被渲染到页面上,所以abstract这个属性至关重要!

// src/core/components/keep-alive.js

export default {
  name: 'keep-alive',
  abstract: true, // 判断此组件是否需要在渲染成真实DOM
  props: {
    include: patternTypes,
    exclude: patternTypes,
    max: [String, Number]
  },
  created() {
    this.cache = Object.create(null) // 创建对象来存储  缓存虚拟dom
    this.keys = [] // 创建数组来存储  缓存key
  },
  mounted() {
    // 实时监听include、exclude的变动
    this.$watch('include', val => {
      pruneCache(this, name => matches(val, name))
    })
    this.$watch('exclude', val => {
      pruneCache(this, name => !matches(val, name))
    })
  },
  destroyed() {
    for (const key in this.cache) { // 删除所有的缓存
      pruneCacheEntry(this.cache, key, this.keys)
    }
  },
  render() {
      // 下面讲
  }
}

原文连接: