App.vue
CompOne.vue
CompTwo.vue
CompThree.vue
main.js
<template>
<h1>Dynamic Components</h1>
<p>With <KeepAlive include="CompOne,CompThree"> only the "CompOne" and "CompThree" components will remember the user input.</p>
<button @click="compNbr++">Next component</button>
<KeepAlive include="CompOne,CompThree">
<component :is="activeComp"></component>
</KeepAlive>
</template>
<script>
export default {
data () {
return {
compNbr: 1
}
},
watch: {
compNbr(val) {
if(val>3) {
this.compNbr = 1;
}
}
},
computed: {
activeComp() {
if(this.compNbr === 1) {
return 'comp-one'
}
else if(this.compNbr === 2) {
return 'comp-two'
}
else {
return 'comp-three'
}
}
}
}
</script>
<style>
#app {
width: 350px;
margin: 10px;
}
#app > div {
border: solid black 2px;
padding: 10px;
margin-top: 10px;
}
h2 {
text-decoration: underline;
}
</style>
<template>
<div>
<img :src="imgSrc">
<h2>Component One</h2>
<p>Choose food.</p>
<label>
<input type="radio" name="rbgFood"
v-model="imgSrc" :value="'img_apple.svg'" />
Apple
</label>
<label>
<input type="radio" name="rbgFood"
v-model="imgSrc" :value="'img_cake.svg'" />
Cake
</label>
</div>
</template>
<script>
export default {
name: 'CompOne',
data () {
return {
imgSrc: 'img_question.svg'
}
}
}
</script>
<style scoped>
div {
background-color: lightgreen;
}
img {
float: right;
height: 100px;
margin-top: 20px;
}
label:hover {
cursor: pointer;
}
</style>
<template>
<div>
<h2>Component Two</h2>
<input type="text" v-model="msg" placeholder="Write something...">
<p>Your message:</p>
<p><strong>{{ this.msg }}</strong></p>
</div>
</template>
<script>
export default {
name: 'CompTwo',
data () {
return {
msg: ''
}
}
}
</script>
<style scoped>
div {
background-color: lightpink;
}
strong {
background-color: yellow;
padding: 5px;
}
</style>
<template>
<div :style="{ backgroundColor: bgColor }">
<h2>Component Three</h2>
<p>Choose a new background-color:</p>
<input type="color" v-model="bgColor">
<strong>{{ this.bgColor }}</strong>
</div>
</template>
<script>
export default {
name: 'CompThree',
data () {
return {
bgColor: ''
}
}
}
</script>
<style></style>
import { createApp } from 'vue'
import App from './App.vue'
import CompOne from './components/CompOne.vue'
import CompTwo from './components/CompTwo.vue'
import CompThree from './components/CompThree.vue'
const app = createApp(App)
app.component('comp-one', CompOne)
app.component('comp-two', CompTwo)
app.component('comp-three', CompThree)
app.mount('#app')