JAVASCRIPT
Efficiently Managing Dynamic Components with keep-alive
Learn how to use Vue 3's <keep-alive> component to cache inactive dynamic components, preserving their state and avoiding re-renders for improved performance.
<template>
<div>
<button @click="activeComponent = 'ComponentA'">Show Component A</button>
<button @click="activeComponent = 'ComponentB'">Show Component B</button>
<hr>
<keep-alive>
<component :is="activeComponent"></component>
</keep-alive>
</div>
</template>
<script setup>
import { ref } from 'vue';
// Assume ComponentA.vue and ComponentB.vue are imported
// e.g., import ComponentA from './ComponentA.vue';
// For this example, we're using string names, which Vue resolves from registered components or global components.
// In a real setup, you'd likely import them and use `markRaw` if passing component objects.
const activeComponent = ref('ComponentA');
// Example ComponentA.vue content (for context):
// <template><div><h2>Component A</h2><input type="text" v-model="message"> Message: {{ message }}</div></template>
// <script setup> import { ref } from 'vue'; const message = ref(''); </script>
// Example ComponentB.vue content (for context):
// <template><div><h2>Component B</h2><p>This is component B.</p></div></template>
// <script setup></script>
</script>
<style scoped>
button {
margin-right: 10px;
padding: 8px 15px;
cursor: pointer;
}
div {
padding: 20px;
border: 1px solid #eee;
margin-top: 10px;
}
</style>
How it works: This snippet demonstrates the use of Vue 3's `<keep-alive>` component with dynamic components. By wrapping the `<component :is="activeComponent">` tag with `<keep-alive>`, Vue caches inactive component instances. When you switch between `ComponentA` and `ComponentB`, their state (e.g., input values in `ComponentA`) is preserved, and the component isn't re-mounted from scratch, leading to better performance and user experience, especially with forms or complex states.