Dynamic component loading is a bit like manipulating elements, nothing special
CompParent.vue code:
<template>
<div>
<h3>动态组件加载component</h3>
<!-- <CompA></CompA>
<hr>
<CompB></CompB> -->
<button @click="change()">切换</button>
<hr>
<keep-alive>
<component :is="showComp"></component>
</keep-alive>
</div>
</template>
<script>
import CompA from './CompA.vue';
import CompB from './CompB.vue';
export default {
components: {
CompA,
CompB
},
data(){
return{
showComp:"CompA"
}
},
methods:{
change(){
// if(this.showComp == "CompA"){
// this.showComp = "CompB"
// }else{
// this.showComp = "CompA"
// }
this.showComp = this.showComp == "CompA" ? "CompB" : "CompA"
}
}
}
</script>
<style>
</style>
CompA.vue code:
<template>
<div>
<h5>组件A</h5>
<button @click="num = num -5">减少5个</button>
<h5>{
{ num }}</h5>
</div>
</template>
<script>
export default {
data(){
return{
num:100
}
}
}
</script>
<style>
</style>
CompB.vue code:
<template>
<div>
<h5>组件B</h5>
<button @click="num = num + 7">增加7个</button>
<h5>{
{ num }}</h5>
</div>
</template>
<script>
export default {
data() {
return {
num: 100
}
}
}
</script>
<style>
</style>
Effect:
This is component A, reduced to 70
This is component BIncreased to 121
and switched back to A again, the content is cached because <keep-alive>
the tag is used