vue实现页面跳转
Vue 实现页面跳转的方法
在 Vue 中实现页面跳转可以通过以下几种方式,具体取决于项目是否使用 Vue Router。
使用 Vue Router 进行跳转
如果项目配置了 Vue Router,可以通过编程式导航或声明式导航实现跳转。
编程式导航
通过 this.$router.push 或 router.push 方法跳转:
// 字符串路径
this.$router.push('/target-path')
// 对象形式
this.$router.push({ path: '/target-path' })
// 命名路由
this.$router.push({ name: 'RouteName' })
// 带查询参数
this.$router.push({ path: '/target-path', query: { id: 123 } })
// 带哈希
this.$router.push({ path: '/target-path', hash: '#section' })
声明式导航
在模板中使用 <router-link> 组件:
<router-link to="/target-path">跳转</router-link>
<router-link :to="{ name: 'RouteName' }">命名路由跳转</router-link>
<router-link :to="{ path: '/target-path', query: { id: 123 } }">带参数跳转</router-link>
不使用 Vue Router 的跳转
如果项目未使用 Vue Router,可以通过原生 JavaScript 实现页面跳转。
window.location
// 跳转到新页面
window.location.href = '/target-path'
// 带参数跳转
window.location.href = '/target-path?id=123'
window.open
// 新窗口打开
window.open('/target-path', '_blank')
// 当前窗口打开
window.open('/target-path', '_self')
动态路由跳转
对于需要动态生成路径的情况,可以拼接路径或参数:

const id = 123
this.$router.push(`/user/${id}`)
// 或
this.$router.push({ path: `/user/${id}` })
路由跳转的注意事项
- 使用 Vue Router 时,确保路由已正确定义在路由配置中。
- 编程式导航可以通过
this.$router.replace实现替换当前路由(不保留历史记录)。 - 路由跳转前可以通过导航守卫进行拦截或验证。
以上方法覆盖了 Vue 中常见的页面跳转需求,根据项目配置选择合适的方式即可。






