Vue中提供了<component>來掛載不同組件崔赌,使用 is 選擇要展示的組件
效果
案例
index.vue
<template>
<div>
<component :is="cmpName"></component> <br/>
<button @click="changeCmp('cmpone')">第一個(gè)組件</button>
<button @click="changeCmp('cmptwo')">第二個(gè)組件</button>
<button @click="changeCmp('cmpthree')">第三個(gè)組件</button>
</div>
</template>
<script>
// 導(dǎo)入子組件
import cmpone from './cmpone'
import cmptwo from './cmptwo '
import cmpthree from './cmpthree '
export default {
// 注冊組件
components: {
cmpone,
cmptwo,
cmpthree
},
methods: {
changeCmp(cmpName) {
this.cmpName = cmpName
}
},
data(){
return {
cmpName: 'cmpone' //默認(rèn)顯示第一個(gè)組件
}
}
}
</script>
cmpone.vue
<template>
<div>這是子組件1</div>
</template>
cmptow.vue
<template>
<div>這是子組件2</div>
</template>
cmpthree.vue
<template>
<div>這是子組件3</div>
</template>