-
概念:动态组件是通过component中的is属性实现的
-
使用:一般结合keepAlive做缓存组件,最常用于tap选项卡
-
实现
- v-oneComponent.vue
<template>
<div>
<h2>{{tapName}}</h2>
<ul>
<li><span @click="reduce">-</span></li>
<li>{{count}}</li>
<li><span @click="add">-</span></li>
</ul>
</div>
</template>
<script>
export default{
props:{
tapName:String
},
data(){
return{
count:0,
}
},
methods:{
reduce(){
this.count--;
},
add(){
this.count++;
}
}
}
</script>
<style scoped lang="scss">
ul{
display: flex;
flex-direction:row;
}
li{
width: 33.3%;
text-align:center;
.count{
display: inline-block;
width: 30px;
height: 20px;
background: yellow;
}
}
</style>
- v-twoComponent.vue
<template>
<div>
<h2>{{tapNames}}</h2>
<ul>
<li><span @click="reduce">-</span></li>
<li>{{count}}</li>
<li><span @click="add">-</span></li>
</ul>
</div>
</template>
<script>
export default{
props:{
tapNames:String
},
data(){
return{
count:0,
}
},
methods:{
reduce(){
this.count--;
},
add(){
this.count++;
}
}
}
</script>
<style scoped lang="scss">
ul{
display: flex;
flex-direction:row;
}
li{
width: 33.3%;
text-align:center;
.count{
display: inline-block;
width: 30px;
height: 20px;
background: yellow;
}
}
</style>
- dynamic.vue
<template>
<div id="dynamic">
<div class="tap">
<ul>
<li v-for="(item,index) in tapData">
<span :class="tapIndex==index?'red':''" @click="changeTap(item,index)">{{item.label}}</span>
</li>
</ul>
</div>
<div class="content">
<keep-alive>
<component
:is="myCom"
:tapName="tapname"
:tapNames="tapnames">
</component>
</keep-alive>
</div>
</div>
</template>
<script>
import vOneCom from "@/components/v-oneComponent.vue";
import vTwoCom from "@/components/v-twoComponent.vue";
export default{
data(){
return{
tapIndex:0,
tapData:[
{label:"one",name:"vOneCom"},
{label:"two",name:"vTwoCom"}
],
myCom:"vOneCom",
tapname:"",
tapnames:""
}
},
components:{
vOneCom,
vTwoCom
},
mounted(){
this.tapname="tap1";
this.tapnames="tap2"
},
methods:{
changeTap(e,i){
this.tapIndex=i;
this.myCom=e.name;
}
}
}
</script>
<style scoped lang="scss">
.tap{
margin-top: 10px;
ul{
display: flex;
flex-direction:row;
li{
width: 50%;
text-align: center;
span{
// background: red;
padding: 5px;
border:1px solid #ccc;
}
.red{
background: red;
}
}
}
}
</style>
-
显示