App.vue
CompOne.vue
CompTwo.vue
main.js
<template>
<h1>Dynamic Components</h1>
<p>App.vue switches between which component to show.</p>
<button @click="toggleValue = !toggleValue">Switch component</button>
<component :is="activeComp"></component>
</template>
<script>
export default {
data () {
return {
toggleValue: true
}
},
computed: {
activeComp() {
if(this.toggleValue) {
return 'comp-one'
}
else {
return 'comp-two'
}
}
}
}
</script>
<style>
#app {
width: 350px;
margin: 10px;
}
#app > div {
border: solid black 2px;
padding: 10px;
margin-top: 10px;
}
</style>
<template>
<div>
<h2>One!</h2>
<p>This is component one.</p>
</div>
</template>
<script></script>
<style scoped>
div {
background-color: lightgreen;
}
</style>
<template>
<div>
<h2>Two!</h2>
<p>This is component two.</p>
</div>
</template>
<script></script>
<style scoped>
div {
background-color: lightpink;
}
</style>
import { createApp } from 'vue'
import App from './App.vue'
import CompOne from './components/CompOne.vue'
import CompTwo from './components/CompTwo.vue'
const app = createApp(App)
app.component('comp-one', CompOne)
app.component('comp-two', CompTwo)
app.mount('#app')