JAVASCRIPT

Dynamic Component Loading with Vue 3's `<component :is='...'>`

Render components dynamically in Vue 3 based on application state or user input using the powerful `<component :is='...'>` attribute, enabling flexible UI structures.

// src/components/ComponentA.vue
<template>
  <div style="border: 1px solid blue; padding: 15px;">
    <h3>This is Component A</h3>
    <p>Message: {{ message }}</p>
    <button @click="$emit('custom-event', 'Data from A')">Emit Event</button>
  </div>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
const props = defineProps({
  message: String
});
const emits = defineEmits(['custom-event']);
</script>

// src/components/ComponentB.vue
<template>
  <div style="border: 1px solid green; padding: 15px;">
    <h3>This is Component B</h3>
    <p>Value: {{ value }}</p>
  </div>
</template>
<script setup>
import { defineProps } from 'vue';
const props = defineProps({
  value: Number
});
</script>

// src/App.vue
<template>
  <div>
    <h1>Dynamic Component Example</h1>
    <button @click="toggleComponent">Toggle Component</button>
    <p>Last Event Data: {{ eventData }}</p>

    <div style="margin-top: 20px;">
      <component
        :is="currentComponentName"
        :message="componentAProps.message"
        :value="componentBProps.value"
        @custom-event="handleCustomEvent"
      />
    </div>
  </div>
</template>

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

const currentComponent = ref('ComponentA'); // 'ComponentA' or 'ComponentB'
const eventData = ref('');

const currentComponentName = computed(() => {
  return currentComponent.value === 'ComponentA' ? ComponentA : ComponentB;
});

const componentAProps = {
  message: 'Hello from Parent!'
};

const componentBProps = {
  value: 123
};

const toggleComponent = () => {
  currentComponent.value = currentComponent.value === 'ComponentA' ? 'ComponentB' : 'ComponentA';
};

const handleCustomEvent = (data) => {
  eventData.value = data;
  console.log('Custom event received:', data);
};
</script>
How it works: This snippet demonstrates how to dynamically render different components in Vue 3 using the special `<component :is='...'>` syntax. The `App.vue` component uses a reactive `currentComponent` ref to store the name of the component to display. A `computed` property `currentComponentName` then resolves this string name to the actual imported component instance (`ComponentA` or `ComponentB`). When the button is clicked, `currentComponent` is toggled, causing Vue to efficiently swap between `ComponentA` and `ComponentB`, passing appropriate props and listening for emitted events for the active component.

Need help integrating this into your project?

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

Hire DigitalCodeLabs