vue实现组件切换
动态组件切换
使用 Vue 的 <component> 元素配合 is 属性实现动态组件切换。通过改变 is 绑定的组件名来切换不同组件。
<template>
<component :is="currentComponent"></component>
<button @click="currentComponent = 'ComponentA'">显示A</button>
<button @click="currentComponent = 'ComponentB'">显示B</button>
</template>
<script>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'
export default {
components: { ComponentA, ComponentB },
data() {
return {
currentComponent: 'ComponentA'
}
}
}
</script>
路由切换
通过 Vue Router 实现基于路由的组件切换,适合构建单页应用。
// router.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from './views/Home.vue'
import About from './views/About.vue'
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
const router = createRouter({
history: createWebHistory(),
routes
})
<!-- App.vue -->
<template>
<router-view></router-view>
</template>
条件渲染
使用 v-if/v-else 指令根据条件显示不同组件。
<template>
<ComponentA v-if="showComponentA" />
<ComponentB v-else />
<button @click="toggleComponent">切换组件</button>
</template>
<script>
export default {
data() {
return {
showComponentA: true
}
},
methods: {
toggleComponent() {
this.showComponentA = !this.showComponentA
}
}
}
</script>
过渡动画
为组件切换添加过渡效果,提升用户体验。
<template>
<transition name="fade" mode="out-in">
<component :is="currentComponent"></component>
</transition>
</template>
<style>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
opacity: 0;
}
</style>
状态保持
使用 <keep-alive> 缓存组件状态,避免重复渲染。
<template>
<keep-alive>
<component :is="currentComponent"></component>
</keep-alive>
</template>
组件间通信
切换组件时通过 props 或事件总线传递数据。

<template>
<component
:is="currentComponent"
:message="sharedData"
@update="handleUpdate"
></component>
</template>
<script>
export default {
data() {
return {
sharedData: '初始数据'
}
},
methods: {
handleUpdate(newData) {
this.sharedData = newData
}
}
}
</script>






