vue实现切换组件
Vue 实现组件切换的方法
动态组件 <component :is>
使用 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 {
data() {
return {
currentComponent: 'ComponentA'
};
},
components: { ComponentA, ComponentB }
};
</script>
条件渲染 v-if/v-show
通过 v-if 或 v-show 控制组件的显示与隐藏:
<template>
<ComponentA v-if="showComponentA" />
<ComponentB v-if="!showComponentA" />
<button @click="showComponentA = !showComponentA">切换组件</button>
</template>
<script>
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
export default {
data() {
return {
showComponentA: true
};
},
components: { ComponentA, ComponentB }
};
</script>
路由切换(Vue Router)
通过 Vue Router 的路由配置实现页面级组件切换:

- 安装并配置路由:
// router/index.js import { createRouter, createWebHistory } from 'vue-router'; import ComponentA from '../views/ComponentA.vue'; import ComponentB from '../views/ComponentB.vue';
const routes = [ { path: '/a', component: ComponentA }, { path: '/b', component: ComponentB } ];
const router = createRouter({ history: createWebHistory(), routes });

export default router;
2. 在组件中使用 `<router-link>` 或编程式导航:
```html
<template>
<router-link to="/a">显示A</router-link>
<router-link to="/b">显示B</router-link>
<router-view></router-view>
</template>
状态管理(Vuex/Pinia)
通过状态管理工具全局管理当前显示的组件:
// store.js (Pinia示例)
import { defineStore } from 'pinia';
export const useComponentStore = defineStore('component', {
state: () => ({
current: 'ComponentA'
}),
actions: {
toggle() {
this.current = this.current === 'ComponentA' ? 'ComponentB' : 'ComponentA';
}
}
});
<template>
<ComponentA v-if="store.current === 'ComponentA'" />
<ComponentB v-if="store.current === 'ComponentB'" />
<button @click="store.toggle()">切换</button>
</template>
<script setup>
import { useComponentStore } from './store';
const store = useComponentStore();
</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-from, .fade-leave-to {
opacity: 0;
}
</style>






