vue实现前端跳转
路由跳转(Vue Router)
在Vue项目中,通过vue-router实现页面跳转是最常见的方式。需要先安装并配置路由。
安装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
在组件中使用路由跳转:
// 编程式导航
this.$router.push('/about')
// 声明式导航(模板中)
<router-link to="/about">About</router-link>
路由传参
通过路由传递参数有两种主要方式:
动态路由匹配:
// 路由配置
{ path: '/user/:id', component: User }
// 跳转时传递参数
this.$router.push('/user/123')
// 组件中获取参数
this.$route.params.id
查询参数:
this.$router.push({ path: '/user', query: { id: 123 } })
// 组件中获取
this.$route.query.id
命名路由
为路由设置名称可以简化跳转操作:
// 路由配置
{ path: '/user/:id', name: 'user', component: User }
// 跳转时使用名称
this.$router.push({ name: 'user', params: { id: 123 } })
路由守卫
控制路由跳转前后的行为:
// 全局前置守卫
router.beforeEach((to, from, next) => {
// 登录验证等逻辑
next()
})
// 路由独享守卫
{
path: '/admin',
component: Admin,
beforeEnter: (to, from, next) => {
// 验证逻辑
next()
}
}
// 组件内守卫
export default {
beforeRouteEnter(to, from, next) {
// 组件渲染前调用
next()
},
beforeRouteUpdate(to, from, next) {
// 当前路由改变但组件复用时调用
next()
},
beforeRouteLeave(to, from, next) {
// 离开该组件时调用
next()
}
}
动态路由
根据需求动态添加路由:
router.addRoute({
path: '/new',
component: NewComponent
})
// 嵌套路由
router.addRoute('parent', {
path: 'child',
component: ChildComponent
})
路由懒加载
优化性能,按需加载路由组件:
const routes = [
{
path: '/about',
component: () => import('../views/About.vue')
}
]
路由模式
Vue Router支持多种历史模式:
// HTML5模式(需要服务器配置)
createWebHistory()
// Hash模式(无需服务器配置)
createWebHashHistory()
// Memory模式(无URL变化,适合SSR)
createMemoryHistory()
滚动行为
控制页面跳转后的滚动位置:
const router = createRouter({
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
return { top: 0 }
}
}
})
路由元信息
为路由添加自定义数据:
{
path: '/admin',
component: Admin,
meta: { requiresAuth: true }
}
// 在守卫中访问
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})






