vue实现跳转页面
路由配置
在Vue项目中实现页面跳转通常使用Vue Router。确保项目已安装Vue Router,可通过命令npm install vue-router安装。
在src/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>标签实现跳转,相当于HTML的<a>标签:
<router-link to="/about">跳转到About页</router-link>
通过active-class属性可自定义激活状态的样式类名。
编程式导航
在JavaScript代码中通过router.push()方法跳转:
// 在组件方法中
this.$router.push('/about')
// 使用命名路由(需提前在路由配置中定义name属性)
this.$router.push({ name: 'about' })
// 带参数跳转
this.$router.push({ path: '/user', query: { id: 123 } })
路由传参
通过动态路由传递参数,需在路由配置中定义参数占位符:
// router/index.js
{ path: '/user/:id', component: User }
在目标组件中通过$route.params.id获取参数。
使用props解耦:
// 路由配置
{ path: '/user/:id', component: User, props: true }
// User组件
export default {
props: ['id']
}
导航守卫
在路由跳转前后执行逻辑控制:
// 全局前置守卫
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth) {
// 验证逻辑
} else {
next()
}
})
// 组件内守卫
export default {
beforeRouteEnter(to, from, next) {
// 组件渲染前调用
}
}
路由模式
根据需求选择路由模式:

// history模式(需服务器支持)
createWebHistory()
// hash模式(URL带#)
createWebHashHistory()
// memory模式(无URL变化,适合SSR)
createMemoryHistory()






