当前位置:首页 > 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 栏内容)。

    vue缓存实现原理

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

注意事项

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

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

相关文章

vue模版实现原理

vue模版实现原理

Vue 模板实现原理 Vue 的模板实现原理主要涉及模板编译、虚拟 DOM 和响应式系统三个核心部分。以下是详细解析: 模板编译 Vue 模板通过编译器将模板字符串转换为渲染函数。这一过程分为以下几…

vue实现缓存视频

vue实现缓存视频

Vue 实现视频缓存的方法 在 Vue 中实现视频缓存可以通过多种方式完成,包括使用浏览器的缓存机制、Service Worker 或者借助第三方库。以下是几种常见的方法: 使用 Service W…

vue原理与实现

vue原理与实现

Vue 的核心原理 Vue 是一个渐进式 JavaScript 框架,其核心原理包括响应式系统、虚拟 DOM、模板编译和组件化设计。这些机制共同构成了 Vue 的高效开发模式。 响应式系统通过 Ob…

vue顶层实现原理

vue顶层实现原理

Vue 顶层实现原理 Vue 的核心实现原理主要包括响应式系统、虚拟 DOM、模板编译和组件化机制。以下是关键原理的分解: 响应式系统 Vue 通过 Object.defineProperty(Vu…

vue实现强缓存

vue实现强缓存

Vue 实现强缓存的常见方法 在 Vue 项目中实现强缓存通常通过配置 HTTP 缓存头或结合构建工具(如 Webpack)实现。以下是几种典型方法: 配置 Webpack 输出文件名哈希 通过 W…

vue template实现原理

vue template实现原理

Vue Template 的实现原理 Vue 的模板(Template)是通过编译转换成渲染函数(Render Function)的,最终生成虚拟 DOM(Virtual DOM)并渲染到真实 DOM…