Performance: Keep-alive for caching components
This affects page interaction speed by caching component state and reducing re-renders during navigation.
<template>
<keep-alive>
<component :is="currentView" />
</keep-alive>
</template>
<script setup>
import { ref } from 'vue'
const currentView = ref('HomeView')
</script><template> <component :is="currentView" /> </template> <script setup> import { ref } from 'vue' const currentView = ref('HomeView') </script>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Without keep-alive | Destroys and recreates DOM nodes on each switch | Triggers 1 reflow per component switch | High paint cost due to full redraw | [X] Bad |
| With keep-alive | Reuses cached DOM nodes, no destruction | No reflow on cached component switch | Low paint cost, only compositing | [OK] Good |
<keep-alive> component in Vue?<keep-alive> does<keep-alive> component caches inactive components instead of destroying them.keep-alive with a dynamic component named MyComponent?<keep-alive> component wraps around a dynamic component using <component :is="..." />.<keep-alive><component :is="MyComponent" /></keep-alive> correctly wraps <component :is="MyComponent" /> inside <keep-alive>. Options A and C misuse attributes or tags. <keep-alive><MyComponent /></keep-alive> tries to wrap a component tag directly, which is invalid for dynamic components.<keep-alive> <component :is="currentView" /> </keep-alive>
currentView switches between 'ViewA' and 'ViewB'. What happens to the state of 'ViewA' when switching to 'ViewB' and back?<keep-alive>, inactive components are cached, not destroyed.<keep-alive> <MyComponent :is="currentView" /> </keep-alive>
currentView is a string with component name.<component :is="..." /> syntax, not <MyComponent :is="..." />.:is on a named component tag, which is invalid and causes errors.<keep-alive> with the include prop to achieve this?include prop accepts a string or array of component names to cache only those components.include="UserProfile" caches only the 'UserProfile' component and excludes others like 'UserSettings'.Pass the test and this pattern moves unknown