Skip to content

keep-alive

使用 <keep-alive> 组件可以对动态组件进行缓存,从而提高组件的性能和响应速度。

基本实现

当一个组件被包裹在 <keep-alive> 组件内时,该组件实例不会被销毁,而是被缓存起来,以备下次需要渲染时使用。

js
export default {
  name: 'MyKeepAlive',
  abstract: true,
  created() {
    this.cache = Object.create(null)
  },
  destroyed() {
    for (const key in this.cache) {
      this.cache[key].$destroy()
    }
  },
  render() {
    const vNode = this.$slots.default?.[0]
    const componentOptions = vNode?.componentOptions
    if (componentOptions) {
      const { cache } = this
      const key = componentOptions.Ctor.cid
      if (cache[key]) {
        vNode.componentInstance = cache[key]
      } else {
        this.$nextTick(() => {
          cache[key] = vNode.componentInstance
        })
      }
      vNode.data.keepAlive = true
    }
    return vNode
  }
}

vNode.data.keepAlive 标识用于在切换组件时触发 activateddeactivated 生命周期钩子,并不会重新创建和销毁组件实例。

注意

被标识 vNode.data.keepAlive 需要手动调用 $destroy 来销毁。