vue如何实现跳页
在Vue中实现页面跳转
Vue中实现页面跳转主要通过路由功能完成,使用vue-router库是最常见的方式。以下介绍几种常见的跳转方法。
使用router-link组件
router-link是Vue Router提供的组件,用于声明式导航,适合在模板中使用:
<router-link to="/target-page">跳转到目标页</router-link>
可以添加动态参数:

<router-link :to="{ name: 'user', params: { userId: 123 }}">用户页</router-link>
编程式导航
通过this.$router提供的API实现跳转:
// 基本跳转
this.$router.push('/target-page')
// 带参数跳转
this.$router.push({ path: '/user', query: { id: '123' } })
// 命名路由跳转
this.$router.push({ name: 'user', params: { userId: '123' } })
// 替换当前路由(不留下历史记录)
this.$router.replace('/new-path')
// 前进/后退
this.$router.go(1) // 前进1页
this.$router.go(-1) // 后退1页
路由配置
需要先在路由配置文件中定义路由:

const routes = [
{
path: '/target-page',
name: 'TargetPage',
component: TargetPageComponent
},
{
path: '/user/:userId',
name: 'user',
component: UserComponent
}
]
动态路由匹配
可以通过参数实现动态路由:
// 路由配置
{
path: '/user/:id',
component: User
}
// 跳转时传递参数
this.$router.push('/user/123')
// 组件内获取参数
this.$route.params.id
导航守卫
可以在跳转前后添加逻辑:
router.beforeEach((to, from, next) => {
// 跳转前逻辑
next()
})
router.afterEach((to, from) => {
// 跳转后逻辑
})
路由模式配置
Vue Router支持两种路由模式:
const router = new VueRouter({
mode: 'history', // 或'hash'
routes
})
- hash模式:URL中有#符号
- history模式:需要服务器配置支持






