← Back to Vue.js Course | Chapter 4: Components | Lesson 6 of 7

Dynamic components

The component tag with the is attribute swaps which component is displayed at runtime.

In this page:

  1. Dynamic components
Syntax
markup
<component :is="currentComponent"></component>

Dynamic components

Bind :is to a component name or definition and Vue renders that component in place. It is ideal for tabs and wizards. Wrap it in keep-alive to preserve each component's state when switching. Note that is on native elements uses a different form.

Note: Combine component :is with keep-alive so tabs remember their state.

Example: Dynamic components

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
  <button @click="current = 'tab-a'">A</button>
  <button @click="current = 'tab-b'">B</button>
  <component :is="current"></component>
</div>
<script>
  const app = Vue.createApp({ data() { return { current: "tab-a" }; } });
  app.component("tab-a", { template: "<p>This is tab A</p>" });
  app.component("tab-b", { template: "<p>This is tab B</p>" });
  app.mount("#app");
  document.querySelectorAll("button")[1].click();
  Vue.nextTick(() => console.log("now showing:", document.querySelector("p").textContent));
</script>
</body>
</html>

<!-- Output:
Rendered: ABThis is tab B
console: now showing: This is tab B
-->
Live Example
Related Topics
Common Mistakes
  1. Passing a string for an unregistered component
  2. Losing state when switching without keep-alive
  3. Reactive proxies wrapping component objects
Chapter Summary
  • <component :is="name"> switches views
  • Great for tabs
  • keep-alive preserves state
  • Components must be registered
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.