← Back to all snippets
JAVASCRIPT

Dynamic Component Rendering with Keep-Alive in Vue 3

Learn to dynamically render different components based on data using Vue 3's `<component :is='...'>` and optimize performance with `<keep-alive>` to preserve component state.

<template>
  <div>
    <button @click="currentComponent = 'ComponentA'">Show Component A</button>
    <button @click="currentComponent = 'ComponentB'">Show Component B</button>

    <div style="border: 1px solid #ccc; padding: 20px; margin-top: 20px;">
      <!-- The component will be rendered here dynamically -->
      <keep-alive>
        <component :is="currentComponent"></component>
      </keep-alive>
    </div>
  </div>
</template>

<script setup>
import { ref, shallowRef } from 'vue';
import ComponentA from './components/ComponentA.vue';
import ComponentB from './components/ComponentB.vue';

// Use shallowRef for components to avoid unnecessary deep reactivity
const currentComponent = shallowRef(ComponentA);

const components = {
  ComponentA,
  ComponentB
};
</script>

// components/ComponentA.vue
<template>
  <div>
    <h3>Component A</h3>
    <p>This is component A. Its state should be preserved.</p>
    <input type="text" v-model="message" placeholder="Type something..." />
    <p>Input: {{ message }}</p>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

const message = ref('');

onMounted(() => console.log('Component A Mounted'));
onUnmounted(() => console.log('Component A Unmounted'));
</script>

// components/ComponentB.vue
<template>
  <div>
    <h3>Component B</h3>
    <p>This is component B. Its state should be preserved.</p>
    <input type="number" v-model="count" placeholder="Enter a number..." />
    <p>Count: {{ count }}</p>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

const count = ref(0);

onMounted(() => console.log('Component B Mounted'));
onUnmounted(() => console.log('Component B Unmounted'));
</script>
How it works: This snippet demonstrates dynamic component rendering using the `<component :is="currentComponent">` syntax in Vue 3. It allows switching between different components based on a reactive variable (`currentComponent`). The crucial addition is `<keep-alive>`, which wraps the dynamic component. `<keep-alive>` ensures that inactive component instances are not destroyed but merely deactivated, preserving their state (like input values) and preventing re-rendering costs when they are switched back, improving performance and user experience.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs