当前位置:首页 > VUE

vue缓存实现原理

2026-01-17 01:48:09VUE

Vue 缓存实现原理

Vue 中的缓存主要通过 keep-alive 组件实现,用于缓存动态组件或路由组件,避免重复渲染和销毁,提升性能。

keep-alive 的核心机制

keep-alive 是一个抽象组件,不会渲染成 DOM 元素。它通过 includeexcludemax 属性控制哪些组件需要缓存。

  • 缓存策略keep-alive 内部维护一个缓存对象 cache,以组件的 nametag 作为键,存储组件的 VNode(虚拟节点)。
  • 生命周期钩子:被缓存的组件会触发 activateddeactivated 钩子,而非 createddestroyed
  • LRU 算法:当缓存数量超过 max 时,keep-alive 会使用 LRU(最近最少使用)策略淘汰最久未使用的组件。

实现缓存的关键代码

Vue 源码中 keep-alive 的核心逻辑如下:

// 简化版源码
export default {
  name: 'keep-alive',
  abstract: true, // 标记为抽象组件

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

  created() {
    this.cache = Object.create(null) // 缓存对象
    this.keys = [] // 缓存键集合(用于 LRU)
  },

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

  render() {
    const slot = this.$slots.default
    const vnode = getFirstComponentChild(slot) // 获取第一个子组件
    const componentOptions = vnode && vnode.componentOptions

    if (componentOptions) {
      const name = getComponentName(componentOptions)
      const { include, exclude } = this

      // 检查是否需要缓存
      if (
        (include && (!name || !matches(include, name))) ||
        (exclude && name && matches(exclude, name))
      ) {
        return vnode
      }

      const { cache, keys } = this
      const key = vnode.key == null
        ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '')
        : vnode.key

      // 命中缓存时直接返回缓存的 VNode
      if (cache[key]) {
        vnode.componentInstance = cache[key].componentInstance
        remove(keys, key)
        keys.push(key) // 更新 LRU 顺序
      } else {
        cache[key] = vnode
        keys.push(key)
        if (this.max && keys.length > parseInt(this.max)) {
          pruneCacheEntry(cache, keys[0], keys, this._vnode)
        }
      }

      vnode.data.keepAlive = true // 标记为已缓存
    }
    return vnode || (slot && slot[0])
  }
}

缓存的实际应用场景

  • 路由切换优化:结合 Vue Router 缓存页面组件,避免重复加载数据。

    <keep-alive>
      <router-view></router-view>
    </keep-alive>
  • 动态组件切换:缓存频繁切换的组件(如 Tab 栏内容)。

    <keep-alive :include="['ComponentA', 'ComponentB']">
      <component :is="currentComponent"></component>
    </keep-alive>

注意事项

  • 组件必须命名:被缓存的组件需通过 name 选项声明名称,否则 include/exclude 无法生效。
  • 数据更新问题:缓存的组件不会触发 mounted,需通过 activated 钩子或监听路由参数更新数据。
  • 内存管理:大量缓存可能导致内存占用过高,需合理设置 max 属性。

vue缓存实现原理

标签: 缓存原理
分享给朋友:

相关文章

vue rooter 实现原理

vue rooter 实现原理

Vue Router 实现原理 Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。其核心实现原理包括路由匹配、组件渲染和导航守卫等机制。 路由匹配与动态路由 V…

eventbus实现原理vue

eventbus实现原理vue

EventBus 实现原理 EventBus 在 Vue 中通常用于跨组件通信,其核心原理基于发布-订阅模式。通过一个中央事件总线,组件可以订阅事件或触发事件,实现非父子组件间的通信。 核心机制 E…

vue实现页面缓存

vue实现页面缓存

Vue 实现页面缓存的常用方法 使用 <keep-alive> 组件 <keep-alive> 是 Vue 内置组件,用于缓存动态组件或路由组件。通过包裹需要缓存的组件,可以保…

vue keepalive 实现原理

vue keepalive 实现原理

Vue KeepAlive 实现原理 Vue 的 KeepAlive 是一个内置组件,用于缓存不活动的组件实例,避免重复渲染,提升性能。以下是其核心实现原理: 缓存机制 KeepAlive 通过维护…

vue实现原理书籍

vue实现原理书籍

以下是关于Vue实现原理的推荐书籍和学习资源,涵盖核心机制、源码解析及实践应用: 深入理解Vue核心机制 《Vue.js设计与实现》 作者霍春阳,系统剖析Vue 3的响应式系统、虚拟DOM、编译器等…

vue实现组件缓存

vue实现组件缓存

Vue 组件缓存的实现方法 在 Vue 中实现组件缓存通常使用 <keep-alive> 内置组件,它可以缓存不活动的组件实例,避免重复渲染和销毁。 基本用法 <keep-aliv…