vue按钮实现页面跳转
使用 router-link 实现跳转
在 Vue 中可以通过 router-link 组件实现页面跳转,这是 Vue Router 提供的声明式导航方式。适合在模板中直接使用。
<router-link to="/target-page">
<button>跳转到目标页</button>
</router-link>
to 属性指定目标路由路径,可以是字符串路径或路由对象。
编程式导航实现跳转
通过 this.$router.push() 方法可以在 JavaScript 代码中实现编程式导航。
<button @click="navigateToPage">跳转到目标页</button>
methods: {
navigateToPage() {
this.$router.push('/target-page')
// 或使用命名路由
// this.$router.push({ name: 'targetPage' })
}
}
带参数的跳转
传递参数到目标页面有两种常见方式:
// 通过路径参数
this.$router.push('/user/123')
// 通过查询参数
this.$router.push({
path: '/user',
query: { id: 123 }
})
目标页面通过 $route.params.id 或 $route.query.id 获取参数。
替换当前路由
使用 replace 方法不会在 history 中留下记录:
this.$router.replace('/target-page')
在新标签页打开
如果需要在新标签页打开页面,可以使用原生 a 标签:
<a :href="targetUrl" target="_blank">
<button>新标签页打开</button>
</a>
computed: {
targetUrl() {
return `${window.location.origin}/target-page`
}
}
路由守卫控制跳转
可以通过路由守卫控制跳转逻辑:
router.beforeEach((to, from, next) => {
if (需要登录 && 未登录) {
next('/login')
} else {
next()
}
})
动态路由匹配
定义动态路由时,使用冒号标记参数:
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User }
]
})
跳转时传递参数:
this.$router.push('/user/123')
目标组件通过 this.$route.params.id 获取参数值。







