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

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

相关推荐
烛阴26 分钟前
用 Python 揭秘 IP 地址背后的地理位置和信息
前端·python
前端开发爱好者34 分钟前
尤雨溪官宣:"新玩具" 比 Prettier 快 45 倍!
前端·javascript·vue.js
why技术34 分钟前
从18w到1600w播放量,我的一点思考。
java·前端·后端
欧阳呀40 分钟前
Vue+element ui导入组件封装——超级优雅版
前端·javascript·vue.js·elementui
清风徐来QCQ43 分钟前
css总结
前端
天***88962 小时前
js封装一个双精度算法实现
开发语言·前端·javascript
Algebraaaaa2 小时前
什么是前端、后端与全栈开发,Qt属于什么?
开发语言·前端·qt
胡斌附体2 小时前
使用Electron创建helloworld程序
前端·javascript·electron·nodejs·pc
toobeloong2 小时前
Electron 从低版本升级到高版本 - webview通信的改造
前端·javascript·electron