Performance: Keep-alive for expensive components
This affects the rendering speed and responsiveness by caching component state and DOM to avoid re-creation on each render.
<template>
<keep-alive>
<ExpensiveComponent v-if="show" />
</keep-alive>
</template>
<script setup>
import ExpensiveComponent from './ExpensiveComponent.vue'
import { ref } from 'vue'
const show = ref(true)
</script><template> <ExpensiveComponent v-if="show" /> </template> <script setup> import ExpensiveComponent from './ExpensiveComponent.vue' import { ref } from 'vue' const show = ref(true) </script>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Without keep-alive | Creates and destroys DOM nodes each toggle | Triggers full reflow on each toggle | High paint cost due to DOM rebuild | [X] Bad |
| With keep-alive | Reuses cached DOM nodes, minimal DOM ops | No reflow from component recreation | Low paint cost, only visibility changes | [OK] Good |
<keep-alive> in Vue?<keep-alive> does<keep-alive> caches components so they don't reload when toggled.keep-alive in Vue 3?<keep-alive> tag wraps the dynamic <component> with :is binding.<keep-alive><component :is="currentView" /></keep-alive> correctly wraps <component :is="currentView" /> inside <keep-alive>. Others misuse attributes or tags.<keep-alive include="CompA,CompB"> <component :is="currentComp" /> </keep-alive>
currentComp changes from 'CompA' to 'CompC' and back to 'CompA', what happens to the state of 'CompA'?include attribute caches only components named 'CompA' and 'CompB'.<keep-alive exclude="CompB"> <component :is="currentComp" /> </keep-alive>
exclude attribute prevents caching only for 'CompB'. Other components like 'CompA' remain cached.CompX and CompY. You want to cache CompX but not CompY. Which is the best way to use <keep-alive> to achieve this?CompX, not CompY.include="CompX" caches only CompX. CompY won't be cached.CompX caches everything except CompX (wrong). Include CompY caches only CompY (wrong). No filters caches all (wrong).Pass the test and this pattern moves unknown