vue实现跳转
Vue 实现页面跳转的方法
在 Vue 中实现页面跳转可以通过多种方式,以下是常见的几种方法:
使用 router-link 组件
router-link 是 Vue Router 提供的组件,用于声明式导航,适合在模板中使用。
<router-link to="/about">跳转到关于页面</router-link>
可以通过 :to 绑定动态路径:
<router-link :to="{ name: 'user', params: { userId: 123 }}">用户页面</router-link>
使用编程式导航
通过 this.$router.push 或 this.$router.replace 方法实现跳转,适合在脚本中触发。
// 跳转到指定路径
this.$router.push('/about');
// 使用命名路由
this.$router.push({ name: 'user', params: { userId: 123 } });
// 替换当前路由(不保留历史记录)
this.$router.replace('/login');
路由传参
跳转时可以传递参数,常见方式包括 params 和 query。
// 通过 params 传参
this.$router.push({ name: 'user', params: { userId: 123 } });
// 通过 query 传参
this.$router.push({ path: '/user', query: { userId: 123 } });
接收参数:
// 接收 params
this.$route.params.userId;
// 接收 query
this.$route.query.userId;
动态路由跳转
动态路由通过路径参数实现跳转,适用于需要动态生成路由的场景。
定义路由:
{
path: '/user/:userId',
name: 'user',
component: User
}
跳转时传递参数:
this.$router.push('/user/123');
导航守卫控制跳转
通过导航守卫可以在跳转前后执行逻辑,例如权限验证。
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login');
} else {
next();
}
});
外部链接跳转
对于非 Vue 路由的跳转,可以使用 window.location。
window.location.href = 'https://example.com';
新窗口打开页面
使用 router-link 或编程式导航实现新窗口打开。
<router-link :to="{ path: '/about' }" target="_blank">新窗口打开</router-link>
编程式导航:

const routeData = this.$router.resolve({ path: '/about' });
window.open(routeData.href, '_blank');
以上方法涵盖了 Vue 中常见的跳转场景,根据具体需求选择合适的方式。






