vue实现导航跳转
Vue 实现导航跳转的方法
使用 <router-link>
Vue Router 提供了 <router-link> 组件用于声明式导航。通过 to 属性指定目标路由路径或命名路由。
<router-link to="/home">首页</router-link>
<router-link :to="{ name: 'user', params: { id: 1 }}">用户详情</router-link>
编程式导航
通过 this.$router.push() 或 this.$router.replace() 方法实现动态跳转。

// 跳转到指定路径
this.$router.push('/home')
// 带参数跳转
this.$router.push({ path: '/user', query: { id: 1 }})
// 命名路由跳转
this.$router.push({ name: 'profile', params: { username: 'test' }})
// 替换当前路由(不保留历史记录)
this.$router.replace('/login')
导航守卫
在路由跳转前执行逻辑,例如权限验证。
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
动态路由匹配
通过路由参数实现动态路径匹配。

const routes = [
{ path: '/user/:id', component: User }
]
访问 /user/123 时可通过 this.$route.params.id 获取参数值。
重定向和别名
配置路由时设置重定向或别名。
const routes = [
{ path: '/home', redirect: '/' },
{ path: '/', alias: '/welcome' }
]
导航传参方式对比
| 方式 | 特点 | 示例 |
|---|---|---|
| params | 路径中显示参数 | /user/1 |
| query | URL 查询参数 | /user?id=1 |
| props | 组件解耦 | { props: true } |
注意事项
- 使用
params时需配合命名路由 query参数会显示在 URL 中- 路由变化后组件实例会复用,需通过监听
$route或使用导航守卫处理数据更新






