Switching Components in Vue
Switching components means trading one component for another in the same spot. The component element with :is picks which component to draw.
The switcher
The component element draws HomeView while view is home.
<component :is="view === 'home' ? HomeView : AboutView" />Swap on click
showAbout sets view to about.
view.value = 'about'Two views
Each view is a small component with its own template.
const HomeView = defineComponent({
template: `<p>Welcome home.</p>`
})Example
<script setup>
import { ref, defineComponent } from 'vue'
const HomeView = defineComponent({
template: `<p>Welcome home.</p>`
})
const AboutView = defineComponent({
template: `<p>About this app.</p>`
})
const view = ref('home')
function showHome() {
view.value = 'home'
}
function showAbout() {
view.value = 'about'
}
</script>
<template>
<div>
<button @click="showHome">Home</button>
<button @click="showAbout">About</button>
<component :is="view === 'home' ? HomeView : AboutView" />
</div>
</template>
Key points
- The component element draws whichever component its :is value names.
- :is takes a component, and Vue draws that component in its place.
- A ref holds a short word for the current view, so a click can swap it.
- Each button sets the ref to a different word.
- Only the chosen component appears on the page.
In this example, HomeView and AboutView are two small components. view is a ref with the word home. The component element draws HomeView while view is home and AboutView while view is about. showHome and showAbout set the ref to each word. The first render shows Welcome home. A verified variant with view set to about shows About this app.
Note
:is also takes a string with a registered component name.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which element switches between components?