Vue中 keep-alive 详解

是 Vue 内置的一个抽象组件,可以将其包裹的动态组件进行缓存,以避免多次重渲染,从而提高应用的性能。

使用方式:

<keep-alive>
  <component :is="currentComponent"></component>
</keep-alive>

当 currentComponent 改变时, 会根据其 key 属性的值来决定是否缓存当前组件实例。如果 key 相同,则使用缓存的组件实例,否则销毁旧实例,重新创建新实例。

下面是 的一些常用属性:

include: 字符串或正则表达式,只有匹配的组件会被缓存。
exclude: 字符串或正则表达式,不匹配的组件会被缓存。
max: 数字,指定缓存的最大组件数,超出则会按照 LRU 策略进行清除。
需要注意的是,由于缓存的组件实例会保留其状态,因此需要在使用缓存组件时注意对其状态的管理,以避免状态污染。

以下是一个示例,演示如何使用 来缓存组件:

<template>
  <div>
    <button @click="toggle">Toggle Component</button>
    <keep-alive>
      <component :is="currentComponent"></component>
    </keep-alive>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentComponent: 'A',
      components: ['A', 'B', 'C']
    }
  },
  methods: {
    toggle() {
      const currentIndex = this.components.indexOf(this.currentComponent)
      this.currentComponent = this.components[(currentIndex + 1) % this.components.length]
    }
  }
}
</script>

在这个示例中,我们使用一个按钮来切换三个不同的组件。由于使用了 ,每个组件只会被创建一次,当切换回已缓存的组件时,它的状态将被恢复。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值