一、使用条件渲染 (v-if)
<template>
<div>
<button @click="currentView = 'ComponentA'">Show Component A</button>
<button @click="currentView = 'ComponentB'">Show Component B</button>
<component-a v-if="currentView === 'ComponentA'"></component-a>
<component-b v-if="currentView === 'ComponentB'"></component-b>
</div>
</template>
<script>
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
export default {
data() {
return {
currentView: 'ComponentA'
};
},
components: {
ComponentA,
ComponentB
}
};
</script>
二、使用动态组件 (component)
<template>
<div>
<button @click="currentView = 'ComponentA'">Show Component A</button>
<button @click="currentView = 'ComponentB'">Show Component B</button>
<component :is="currentView"></component>
</div>
</template>
<script>
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
export default {
data() {
return {
currentView: 'ComponentA'
};
},
components: {
ComponentA,
ComponentB
}
};
</script>
三、点击按钮切换组件
<template>
<div>
<button @click="toggleComponent">切换组件</button>
<div v-if="showComponent">
<ComponentA />
</div>
<div v-else>
<ComponentB />
</div>
</div>
</template>
<script>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'
export default {
data() {
return {
showComponent: true
}
},
methods: {
toggleComponent() {
this.showComponent = !this.showComponent
}
},
components: {
ComponentA,
ComponentB
}
}
</script>
<template>
<div>
<button @click="toggleComponent">切换组件</button>
<transition name="fade">
<component :is="currentComponent" />
</transition>
</div>
</template>
<script>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'
export default {
data() {
return {
currentComponent: 'ComponentA'
}
},
methods: {
toggleComponent() {
this.currentComponent = this.currentComponent === 'ComponentA' ? 'ComponentB' : 'ComponentA'
}
},
components: {
ComponentA,
ComponentB
}
}
</script>
<style>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
opacity: 0;
}
</style>