0
0
Vueframework~5 mins

Dynamic components with is attribute in Vue

Choose your learning style9 modes available
Introduction

Dynamic components let you switch which component shows on the page without reloading. This helps make your app feel smooth and fast.

Showing different views based on user choices, like tabs or menus.
Loading different forms or content blocks without changing the page.
Building a dashboard where widgets can change dynamically.
Creating a step-by-step wizard where each step is a different component.
Syntax
Vue
<component :is="componentName"></component>
The tag is a special Vue element that renders the component named in the 'is' attribute.
You can bind 'is' to a variable to change the component dynamically.
Examples
Renders the component stored in the currentView variable.
Vue
<component :is="currentView"></component>
Renders the MyButton component directly.
Vue
<component is="MyButton"></component>
Switches the displayed component based on selectedComponent reactive data.
Vue
<component :is="selectedComponent"></component>
Sample Program

This Vue component shows two buttons. Clicking a button changes which component is shown below. The component tag with :is switches between HelloWorld and GoodbyeWorld components dynamically.

Vue
<template>
  <div>
    <button @click="currentComponent = 'HelloWorld'">Show Hello</button>
    <button @click="currentComponent = 'GoodbyeWorld'">Show Goodbye</button>
    <component :is="currentComponent"></component>
  </div>
</template>

<script>
import { ref } from 'vue'

export default {
  components: {
    HelloWorld: {
      template: '<p>Hello, friend!</p>'
    },
    GoodbyeWorld: {
      template: '<p>Goodbye, friend!</p>'
    }
  },
  setup() {
    const currentComponent = ref('HelloWorld')
    return { currentComponent }
  }
}
</script>
OutputSuccess
Important Notes

Make sure the components you want to switch between are registered in your parent component.

Dynamic components keep their own state unless you force them to reset.

You can also use async components with is for lazy loading.

Summary

Dynamic components let you swap views without reloading the page.

Use the component tag with the is attribute bound to a variable.

This makes your app interactive and flexible for many UI scenarios.