Vue中提供了<component>来挂载不同组件,使用 is 选择要展示的组件
效果
image.png案例
index.vue
<template>
<div>
<component :is="cmpName"></component> <br/>
<button @click="changeCmp('cmpone')">第一个组件</button>
<button @click="changeCmp('cmptwo')">第二个组件</button>
<button @click="changeCmp('cmpthree')">第三个组件</button>
</div>
</template>
<script>
// 导入子组件
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' //默认显示第一个组件
}
}
}
</script>
cmpone.vue
<template>
<div>这是子组件1</div>
</template>
cmptow.vue
<template>
<div>这是子组件2</div>
</template>
cmpthree.vue
<template>
<div>这是子组件3</div>
</template>
网友评论