JAVASCRIPT

Manage Dynamic Components with KeepAlive

Dynamically switch Vue 3 components, preserving state with `<component :is>` and `<KeepAlive>`. Optimizes user experience by caching inactive instances.

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

const currentComponent = ref(markRaw(ComponentA));
const components = {
  ComponentA: markRaw(ComponentA),
  ComponentB: markRaw(ComponentB),
  ComponentC: markRaw(ComponentC),
};

const changeComponent = (componentName) => {
  currentComponent.value = components[componentName];
};
</script>

<template>
  <div>
    <nav>
      <button @click="changeComponent('ComponentA')">Show A</button>
      <button @click="changeComponent('ComponentB')">Show B</button>
      <button @click="changeComponent('ComponentC')">Show C</button>
    </nav>
    <hr>
    <!-- Use KeepAlive to preserve component state when switching -->
    <KeepAlive>
      <component :is="currentComponent"></component>
    </KeepAlive>
  </div>
</template>

/*
// components/ComponentA.vue (Example component)
<script setup>
import { ref, onActivated, onDeactivated } from 'vue';

const count = ref(0);
let intervalId;

onActivated(() => {
  console.log('ComponentA Activated!');
  intervalId = setInterval(() => count.value++, 1000);
});

onDeactivated(() => {
  console.log('ComponentA Deactivated!');
  clearInterval(intervalId);
});
</script>

<template>
  <div>
    <h2>Component A</h2>
    <p>Count: {{ count }}</p>
    <input type="text" placeholder="Type something here">
  </div>
</template>

// components/ComponentB.vue (Example component)
<template>
  <div>
    <h2>Component B</h2>
    <p>This component also preserves state.</p>
    <textarea placeholder="Enter text here..."></textarea>
  </div>
</template>

// components/ComponentC.vue (Example component)
<template>
  <div>
    <h2>Component C</h2>
    <p>Another dynamic component.</p>
  </div>
</template>
*/
How it works: This snippet demonstrates how to dynamically render different components using `<component :is="currentComponent">`. The key feature here is `<KeepAlive>`, which wraps the dynamic component to cache inactive component instances. This prevents components from being unmounted and re-mounted every time you switch, preserving their state (like input values or timers) and improving performance. `markRaw` is used to prevent the component instances from becoming reactive, which can be useful for performance with large component trees.

Need help integrating this into your project?

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

Hire DigitalCodeLabs