1. 效果展示
2. 代码
关键代码: <component :is="currentItem" />
,通过控制 is 的值来决定显示的组件
父组件
// Parent.vue
<template>
<div>
<component :is="currentItem" />
<button @click="handleChange">切换组件</button>
</div>
</template>
<script>
import TestChild from '@/components/TestChild'
import TestChild2 from '@/components/TestChild2'
export default {
components: {
TestChild,
TestChild2
},
data() {
return {
currentItem: 'TestChild'
}
},
methods: {
handleChange() {
if (this.currentItem === 'TestChild') {
this.currentItem = 'TestChild2'
} else {
this.currentItem = 'TestChild'
}
}
}
}
</script>
子组件1
// Child1.vue
<template>
<div>111</div>
</template>
<script>
export default {}
</script>
子组件2
// Child2.vue
<template>
<div>222</div>
</template>
<script>
export default {}
</script>
不忘初心