Vue中 keep-alive 详解

<keep-alive> 是 Vue 内置组件,它可以将动态组件缓存起来,提高组件的渲染性能。

当一个组件被包裹在 <keep-alive> 标签中时,它的状态会被缓存,包括它的实例、生命周期钩子等。当组件被切换时,如果之前已经被渲染过,那么它就会直接从缓存中读取状态并渲染,而不是重新创建一个新的实例。

使用 <keep-alive> 需要注意以下几点:

  1. <keep-alive> 只能用在动态组件或者用 v-if 切换的组件上。
  2. 被包裹的组件必须有一个独特的 key 属性,用于区分不同的缓存组件。
  3. 在缓存中的组件,不会被销毁和重新创建,因此也不会触发 createddestroyed 生命周期钩子,但是 activateddeactivated 生命周期钩子会在组件被缓存和激活时触发。

下面是一个使用 <keep-alive> 的例子:

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

<script>
export default {
  data() {
    return {
      currentComponent: 'ComponentA'
    }
  },
  methods: {
    toggle() {
      this.currentComponent = this.currentComponent === 'ComponentA' ? 'ComponentB' : 'ComponentA'
    }
  },
  components: {
    ComponentA: {
      template: '<div>Component A</div>',
      activated() {
        console.log('Component A activated')
      },
      deactivated() {
        console.log('Component A deactivated')
      }
    },
    ComponentB: {
      template: '<div>Component B</div>',
      activated() {
        console.log('Component B activated')
      },
      deactivated() {
        console.log('Component B deactivated')
      }
    }
  }
}
</script>

在上面的例子中,有两个组件 ComponentAComponentB,它们会在点击按钮时相互切换。这两个组件都被包裹在 <keep-alive> 中,并且它们的 key 属性使用组件名来表示。当组件被缓存起来时,会触发对应组件的 activateddeactivated 生命周期钩子,我们可以在这两个钩子中打印日志来观察组件的激活和停用。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值