【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');
  }
};

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

相关推荐
该换个名儿了2 分钟前
git多个commit合并成一个
前端·git
LaoZhangAI5 分钟前
2025最新OpenAI组织验证失败完全解决方案:8种有效方法彻底修复【实战指南】
前端·后端
国家不保护废物6 分钟前
微信红包算法深度解析:从产品思维到代码实现
javascript·算法·面试
siwangqishiq217 分钟前
Vulkan Tutorial 教程翻译(三) 绘制三角形 2.1 安装
前端
LaughingZhu17 分钟前
PH热榜 | 2025-06-05
前端·人工智能·经验分享·搜索引擎·产品运营
大模型真好玩18 分钟前
最强大模型评测工具EvalScope——模型好不好我自己说了算!
前端·人工智能·python
wxid:yiwoxuan34 分钟前
购物商城网站 Java+Vue.js+SpringBoot,包括商家管理、商品分类管理、商品管理、在线客服管理、购物订单模块
java·vue.js·spring boot·课程设计
隐藏用户_y34 分钟前
JavaScript闭包概念和应用详解
javascript·面试
Dream耀34 分钟前
CSS选择器完全手册:精准控制网页样式的艺术
前端·css·html
wordbaby34 分钟前
React 19 亮点:让异步请求和数据变更也能用 Transition 管理!
前端·react.js