JAVASCRIPT

Vue 3 Dynamic Components with `is` and `KeepAlive`

Understand how to dynamically render different components using the `<component :is='...' />` syntax in Vue 3, enhanced with `<KeepAlive>` for state preservation.

// src/components/TabA.vue
<template>
  <div>
    <h3>Tab A Content</h3>
    <p>This is content for Tab A.</p>
    <input type="text" placeholder="Type something here" />
  </div>
</template>

<script setup>
import { onMounted, onUnmounted } from 'vue';
onMounted(() => console.log('TabA Mounted'));
onUnmounted(() => console.log('TabA Unmounted'));
</script>

// src/components/TabB.vue
<template>
  <div>
    <h3>Tab B Content</h3>
    <p>This is content for Tab B.</p>
    <button @click="count++">Count: {{ count }}</button>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
const count = ref(0);
onMounted(() => console.log('TabB Mounted'));
onUnmounted(() => console.log('TabB Unmounted'));
</script>

// src/App.vue
<template>
  <div>
    <h1>Dynamic Components with KeepAlive</h1>
    <button @click="currentTab = 'TabA'">Show Tab A</button>
    <button @click="currentTab = 'TabB'">Show Tab B</button>

    <hr />

    <!-- Without KeepAlive, component state is lost on switch -->
    <h2>Without KeepAlive</h2>
    <component :is="currentTab" />

    <hr />

    <!-- With KeepAlive, component state is preserved -->
    <h2>With KeepAlive</h2>
    <KeepAlive>
      <component :is="currentTab" />
    </KeepAlive>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import TabA from './components/TabA.vue';
import TabB from './components/TabB.vue';

const currentTab = ref('TabA');
</script>
How it works: This example demonstrates how to use the `<component :is='...' />` dynamic component feature in Vue 3 to switch between different components based on a reactive state. It also showcases the power of `<KeepAlive>`, which intelligently caches inactive component instances. When a component is wrapped by `<KeepAlive>`, its state and DOM elements are preserved when it's switched out, preventing re-rendering and loss of data, as seen with the input field in Tab A and the counter in Tab B.

Need help integrating this into your project?

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

Hire DigitalCodeLabs