Dynamic components
The component tag with the is attribute swaps which component is displayed at runtime.
In this page:
Syntax
<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
<!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
- Passing a string for an unregistered component
- Losing state when switching without keep-alive
- 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: