0
0
VueHow-ToBeginner · 4 min read

How to Use Component is Directive in Vue for Dynamic Components

In Vue, use the <component :is="componentName"></component> syntax to render dynamic components based on the value of componentName. This lets you switch which component shows without changing the template structure.
📐

Syntax

The <component> tag with the is attribute lets you render different components dynamically. The value of is can be a component name string or a component object.

  • <component>: Vue's built-in tag for dynamic components.
  • :is: Binds the component to render dynamically.
  • componentName: A string or component object that decides which component to show.
vue
<component :is="componentName"></component>
💻

Example

This example shows how to switch between two components using the is directive. Clicking buttons changes which component is displayed.

vue
<template>
  <div>
    <button @click="currentComponent = 'HelloWorld'">Show HelloWorld</button>
    <button @click="currentComponent = 'GoodbyeWorld'">Show GoodbyeWorld</button>

    <component :is="currentComponent"></component>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const currentComponent = ref('HelloWorld')

const HelloWorld = {
  template: '<p>Hello, World!</p>'
}

const GoodbyeWorld = {
  template: '<p>Goodbye, World!</p>'
}

const components = { HelloWorld, GoodbyeWorld }

// Register components locally
</script>
Output
Initially shows: Hello, World! Clicking buttons switches text to Goodbye, World! or Hello, World!
⚠️

Common Pitfalls

Common mistakes when using component is include:

  • Not registering components properly before using their names.
  • Passing an invalid or undefined component name, causing nothing to render.
  • Forgetting to use :is as a dynamic binding (missing the colon).

Always ensure the component name matches a registered component or a valid component object.

vue
<!-- Wrong: missing colon, renders literal 'MyComponent' tag -->
<component is="MyComponent"></component>

<!-- Right: dynamic binding with colon -->
<component :is="MyComponent"></component>
📊

Quick Reference

FeatureDescriptionExample
Dynamic component tagUse with :is to render components dynamically
Component nameString or component object to render'HelloWorld' or HelloWorldComponent
Binding syntaxUse colon :is for dynamic binding
FallbackUse with v-if or default component for fallbackUse v-if to show fallback if componentName is invalid

Key Takeaways

Use to render components dynamically in Vue.
Always bind with :is (colon) to make it reactive and dynamic.
Ensure the component name or object is registered and valid before use.
Switching component names changes the rendered component without template changes.
Common errors include missing colon or unregistered component names.