vue怎么实现跳转页面
Vue 实现页面跳转的方法
使用 <router-link> 组件
在模板中使用 <router-link> 组件实现声明式导航,适合在模板中直接使用。
<router-link to="/path">跳转到目标页</router-link>
通过 :to 可以动态绑定路径或命名路由:
<router-link :to="{ name: 'routeName' }">命名路由跳转</router-link>
编程式导航(通过 router.push)
在 JavaScript 中通过 this.$router.push 实现跳转:
// 路径跳转
this.$router.push('/path');
// 命名路由跳转
this.$router.push({ name: 'routeName' });
// 带参数跳转
this.$router.push({ path: '/detail', query: { id: 123 } });
this.$router.push({ name: 'detail', params: { id: 123 } });
路由替换(router.replace)
跳转时不保留当前页面的历史记录:
this.$router.replace('/path');
重定向(router.go)
前进或后退指定步数:
this.$router.go(-1); // 返回上一页
this.$router.go(1); // 前进一页
动态路由参数
在路由配置中定义动态参数:
// router.js 配置
{
path: '/detail/:id',
name: 'detail',
component: DetailPage
}
跳转时传递参数:
this.$router.push({ name: 'detail', params: { id: 123 } });
目标页面通过 this.$route.params.id 获取参数。
导航守卫控制跳转
在路由配置或全局中设置守卫逻辑:
router.beforeEach((to, from, next) => {
if (需要登录验证 && 未登录) {
next('/login');
} else {
next();
}
});
注意事项
query和params区别:query参数显示在 URL 中(如?id=123),params需搭配动态路由使用。- 路由配置:确保目标路径在
router.js中已正确定义。 - 组件内访问路由:通过
this.$route获取当前路由信息,this.$router控制跳转。







