【Vue】Keep alive详解

在 Vue 中,keep-alive 是一个内置组件,用于缓存动态组件实例,避免重复渲染和销毁。这对于提高性能非常有用,特别是在频繁切换的组件中。

基本用法

html 复制代码
<template>
  <div id="app">
    <button @click="currentComponent = 'ComponentA'">Component A</button>
    <button @click="currentComponent = 'ComponentB'">Component B</button>

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

<script>
import ComponentA from './components/ComponentA.vue';
import ComponentB from './components/ComponentB.vue';

export default {
  name: 'App',
  components: {
    ComponentA,
    ComponentB
  },
  data() {
    return {
      currentComponent: 'ComponentA'
    };
  }
};
</script>

解释

  1. 模板部分

    • 使用 <keep-alive> 包裹需要缓存的组件。
    • 使用 <component :is="currentComponent"></component> 动态切换组件。
  2. 脚本部分

    • 导入需要缓存的组件 ComponentAComponentB
    • data 中定义当前显示的组件 currentComponent

属性

keep-alive 组件支持以下属性:

  • include:字符串或正则表达式,指定哪些组件应该被缓存。
  • exclude:字符串或正则表达式,指定哪些组件不应该被缓存。
  • max:数字,指定最多缓存多少个组件实例。

示例

html 复制代码
<template>
  <div id="app">
    <button @click="currentComponent = 'ComponentA'">Component A</button>
    <button @click="currentComponent = 'ComponentB'">Component B</button>

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

<script>
import ComponentA from './components/ComponentA.vue';
import ComponentB from './components/ComponentB.vue';

export default {
  name: 'App',
  components: {
    ComponentA,
    ComponentB
  },
  data() {
    return {
      currentComponent: 'ComponentA'
    };
  }
};
</script>

在这个示例中,只有 ComponentA 会被缓存,而 ComponentB 不会被缓存。

生命周期钩子

keep-alive 组件提供了两个生命周期钩子:

  • activated:当组件被激活时调用。
  • deactivated:当组件被停用时调用。

这些钩子可以用于执行一些特定的操作,例如数据刷新或状态保存。

javascript 复制代码
// ComponentA.vue
export default {
  name: 'ComponentA',
  activated() {
    console.log('ComponentA activated');
  },
  deactivated() {
    console.log('ComponentA deactivated');
  }
};

通过这些钩子,你可以在组件激活和停用时执行特定的操作,进一步优化性能和用户体验。

相关推荐
想学后端的前端工程师7 分钟前
【微前端架构实战指南:从原理到落地】
前端·架构·状态模式
用户68026590511919 分钟前
如何利用 Endpoint Central 提高企业终端管理效率
javascript·后端·面试
Keya21 分钟前
DevEco Studio 使用技巧全面解析
前端·前端框架·harmonyos
_Rookie._22 分钟前
web请求 错误拦截
前端
青鸟北大也是北大29 分钟前
CSS单位与字体样式全解析
前端·css·html
咖啡の猫32 分钟前
TypeScript 开发环境搭建
前端·javascript·typescript
co松柏1 小时前
AI+Excalidraw,用自然语言画手绘风格技术图
前端·人工智能·后端
用户81274828151201 小时前
安卓Settings值原理源码剖析存储最大的字符数量是多少?
前端
用户81274828151201 小时前
安卓14剖析SystemUI的ShadeLogger/LogBuffer日志动态控制输出dumpsy机制
前端
Ankkaya1 小时前
cloudflare + github 实现留言板
前端·github