vue怎样实现页面跳转
Vue 实现页面跳转的方法
在 Vue 中实现页面跳转主要通过路由(Vue Router)完成,以下是几种常见的跳转方式:
使用 <router-link> 组件
通过 Vue Router 提供的 <router-link> 组件实现声明式导航,适合模板中的跳转:
<router-link to="/home">跳转到首页</router-link>
带参数的动态路由跳转:
<router-link :to="{ name: 'user', params: { userId: 123 }}">用户页面</router-link>
编程式导航
通过 this.$router.push 方法在 JavaScript 中实现跳转:
// 路径跳转
this.$router.push('/home');
// 命名路由跳转(带参数)
this.$router.push({ name: 'user', params: { userId: 123 } });
// 带查询参数跳转
this.$router.push({ path: '/user', query: { id: 123 } });
替换当前路由
使用 this.$router.replace 替换当前路由(不保留历史记录):
this.$router.replace('/new-page');
路由重定向
在路由配置中设置 redirect 实现自动跳转:
const routes = [
{ path: '/old-path', redirect: '/new-path' }
];
前进/后退导航
使用 this.$router.go 控制历史记录前进或后退:
// 后退一步
this.$router.go(-1);
// 前进两步
this.$router.go(2);
路由传参方式对比
-
params 传参
需在路由配置中定义参数:{ path: '/user/:userId', name: 'user', component: User }获取参数:
this.$route.params.userId -
query 传参
无需路由配置,通过?传递:this.$router.push({ path: '/user', query: { id: 123 } })获取参数:
this.$route.query.id
注意事项
- 使用
params时需通过name跳转,path会忽略参数 query参数会显示在 URL 中(如/user?id=123)- 路由配置需提前在
router/index.js中定义好路径和组件映射







