vue界面实现页面切换
Vue 实现页面切换的方法
使用 Vue Router 进行路由切换
Vue Router 是 Vue.js 官方推荐的路由管理工具,适合单页面应用(SPA)的页面切换。
安装 Vue Router:
npm install vue-router
配置路由:
// router/index.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
})
export default router
在组件中使用路由:

<template>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
<router-view></router-view>
</template>
使用动态组件切换
适合在同一个页面中切换显示不同组件的情况。
<template>
<button @click="currentComponent = 'ComponentA'">Show A</button>
<button @click="currentComponent = 'ComponentB'">Show B</button>
<component :is="currentComponent"></component>
</template>
<script>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'
export default {
components: { ComponentA, ComponentB },
data() {
return {
currentComponent: 'ComponentA'
}
}
}
</script>
使用条件渲染
适合简单的显示/隐藏切换场景。

<template>
<button @click="showComponent = !showComponent">Toggle</button>
<ComponentA v-if="showComponent" />
<ComponentB v-else />
</template>
<script>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'
export default {
components: { ComponentA, ComponentB },
data() {
return {
showComponent: true
}
}
}
</script>
使用过渡动画
为页面切换添加动画效果。
<template>
<router-view v-slot="{ Component }">
<transition name="fade" mode="out-in">
<component :is="Component" />
</transition>
</router-view>
</template>
<style>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.3s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
</style>
使用状态管理
当需要跨组件共享页面状态时,可以结合 Vuex 或 Pinia。
// store/index.js
import { defineStore } from 'pinia'
export const usePageStore = defineStore('page', {
state: () => ({
currentPage: 'home'
}),
actions: {
setPage(page) {
this.currentPage = page
}
}
})
在组件中使用:
<template>
<button @click="pageStore.setPage('about')">Go to About</button>
<Home v-if="pageStore.currentPage === 'home'" />
<About v-else-if="pageStore.currentPage === 'about'" />
</template>
<script>
import { usePageStore } from '@/stores/page'
import Home from './Home.vue'
import About from './About.vue'
export default {
components: { Home, About },
setup() {
const pageStore = usePageStore()
return { pageStore }
}
}
</script>






