vue实现多个页面转化
Vue 实现多页面转换的方法
使用 Vue Router 实现单页应用 (SPA) 路由切换
在 Vue 中,通过 Vue Router 可以实现单页应用内的页面切换。安装 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
在组件中使用 <router-link> 进行导航,<router-view> 作为路由出口显示匹配的组件。
<template>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
<router-view></router-view>
</template>
配置多页面应用 (MPA) 的多个入口
如果需要构建真正的多页面应用(每个页面有独立的 HTML 文件),可以通过修改 Vue CLI 或 Vite 配置实现。
在 vue.config.js 中配置多个页面入口:
// vue.config.js
module.exports = {
pages: {
index: {
entry: 'src/main.js',
template: 'public/index.html',
filename: 'index.html'
},
about: {
entry: 'src/about/main.js',
template: 'public/about.html',
filename: 'about.html'
}
}
}
每个页面需要独立的入口文件(如 src/about/main.js)和模板文件(如 public/about.html)。
动态路由与参数传递
Vue Router 支持动态路由匹配,可以通过参数实现页面间的数据传递。
// 路由配置
{ path: '/user/:id', component: User }
在组件中访问路由参数:
this.$route.params.id
使用 <router-link> 传递参数:
<router-link :to="{ name: 'user', params: { id: 123 }}">User</router-link>
路由导航守卫控制页面跳转
通过导航守卫可以在路由切换前后执行逻辑,如权限验证、页面跳转取消等。
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
页面过渡动画效果
使用 Vue 的过渡系统为路由切换添加动画效果。
<router-view v-slot="{ Component }">
<transition name="fade">
<component :is="Component" />
</transition>
</router-view>
添加 CSS 过渡样式:
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
嵌套路由实现复杂布局
对于有嵌套布局的页面,可以使用嵌套路由配置。
{
path: '/settings',
component: SettingsLayout,
children: [
{ path: 'profile', component: Profile },
{ path: 'account', component: Account }
]
}
在父组件中放置 <router-view> 作为子路由出口。
编程式导航控制页面跳转
除了 <router-link>,还可以通过代码实现页面跳转。
// 字符串路径
router.push('/about')
// 带参数
router.push({ path: '/user', query: { id: '123' } })
// 替换当前路由
router.replace({ path: '/home' })
路由懒加载优化性能
对于大型应用,可以使用懒加载拆分代码块,按需加载路由组件。
const About = () => import('./views/About.vue')
保持页面状态
默认情况下,Vue Router 会在路由切换时销毁并重建组件。使用 <keep-alive> 可以缓存组件状态。
<router-view v-slot="{ Component }">
<keep-alive>
<component :is="Component" />
</keep-alive>
</router-view>






