目录
一、路由传参概述
二、动态路由参数(params)
2.1 基础用法
2.2 传递参数
2.3 获取参数
2.4 可选参数
2.5 多个参数与正则约束
2.6 多 params 的详细用法
多个可选参数的使用
路由配置
获取可选参数
三、查询参数(Query)
3.1 特点与应用场景
3.2 传递参数
3.3 获取参数
3.4 保留当前查询参数
四、命名视图传参
五、props 解耦(推荐方式)
六、状态管理(Pinia/Vuex)
6.1 使用 Pinia 示例
七、路由元信息(meta)
八、不同传参方式对比
九、最佳实践
十、常见问题与解决方案
Vue 3 路由传参使用指南
在 Vue 3 应用中,路由传参是实现页面间数据传递的核心功能。Vue Router 4 提供了多种传参方式,适用于不同的场景。这个指南将介绍如何在 Vue 3 中使用路由传递参数。
动态路由参数通过在路由路径中定义 :参数名
来传递。参数将成为 URL 的一部分,适用于 SEO 或书签场景。
路由配置:
const routes = [
{ path: '/user/:id', name: 'UserDetail', component: UserDetail },
{ path: '/post/:id/:action?', name: 'Post', component: Post } // 可选参数
];
通过路由链接或编程式导航传递参数。
用户详情
this.$router.push({ name: 'UserDetail', params: { id: 123 } });
在目标组件中使用 useRoute
来获取路由参数。
通过在参数后添加 ?
标记,使其成为可选参数。
{ path: '/user/:id?', component: User }
可以使用正则表达式来约束参数格式,例如:
{ path: '/article/:id(\\d+)/:action(edit|view)', component: Article }
params
的详细用法可以传递多个动态参数,并根据需求获取:
路由配置:
const routes = [
{ path: '/product/:category/:id', name: 'ProductDetail', component: ProductDetail },
{ path: '/order/:orderId/:status?', name: 'OrderInfo', component: OrderInfo },
{ path: '/blog/:year/:month/:day/:postId', name: 'BlogArticle', component: BlogArticle }
];
参数传递:
电子产品详情
获取参数:
结合 props
解耦:
{
path: '/product/:category/:id',
name: 'Product',
component: ProductComponent,
props: (route) => ({ category: route.params.category, id: Number(route.params.id) })
}
在 Vue 3 中,处理多个可选参数的情况需要在路由配置中通过适当的方式来设置。多个可选参数可以通过在路由路径中给每个参数后添加 ?
来标记为可选。多个参数之间通过斜杠 /
分隔。
多个可选参数通过在路径中添加 ?
来实现,例如:
const routes = [
{ path: '/user/:id?/:name?', name: 'UserDetail', component: UserDetail },
{ path: '/product/:category?/:id?', name: 'ProductDetail', component: ProductDetail }
];
传递可选参数
在 router-link
或 router.push
中传递多个可选参数:
用户详情
用户详情
通过 useRoute()
获取传递的多个可选参数:
查询参数通过 URL 的查询字符串传递,适合传递可选参数、过滤条件等。
查询参数不会影响路由匹配,适合频繁变化的参数。
通过路由链接:
第二页
通过编程式导航:
this.$router.push({ name: 'UserList', query: { page: 2, size: 10 } });
通过 router.push
修改部分查询参数,并保持其他参数:
const route = useRoute();
router.push({ name: 'UserList', query: { ...route.query, page: 2 } });
在路由配置中,可以为多个视图传递不同的参数。
路由配置:
const routes = [
{
path: '/user/:id',
components: {
default: UserProfile,
sidebar: UserSidebar
},
props: {
default: true,
sidebar: { admin: true }
}
}
];
组件接收参数:
使用 props
选项将路由参数解耦为组件的普通 props
,提高组件的复用性。
路由配置:
const routes = [
{ path: '/user/:id', name: 'User', component: UserComponent, props: true },
{
path: '/search',
name: 'Search',
component: SearchComponent,
props: (route) => ({ query: route.query.q, page: Number(route.query.page) || 1 })
}
];
组件接收参数:
对于复杂或跨页面的数据传递,推荐使用状态管理库。
定义 Store:
// store/user.js
import { defineStore } from 'pinia';
export const useUserStore = defineStore('user', {
state: () => ({ userId: null, userInfo: {} }),
actions: {
setUserId(id) { this.userId = id; },
fetchUserInfo() { return fetch(`/api/users/${this.userId}`).then(res => res.json()); }
}
});
使用 Store:
路由配置中可以添加元信息(meta
),例如权限控制、页面标题等。
路由配置:
const routes = [
{
path: '/dashboard',
name: 'Dashboard',
component: Dashboard,
meta: { requiresAuth: true, title: '控制面板' }
}
];
获取元信息:
全局导航守卫中使用:
router.beforeEach((to, from) => {
if (to.meta.requiresAuth && !isAuthenticated()) {
return { name: 'Login' };
}
});
方式 | 适用场景 | URL 可见 | 类型 | 组件解耦 |
---|---|---|---|---|
动态路由参数 | 必需参数、SEO 友好 | 是 | 字符串 | 低 |
查询参数 | 可选参数、过滤条件 | 是 | 字符串 | 低 |
props | 组件解耦、复用 | 否 | 自定义 | 高 |
状态管理 | 复杂数据、跨页面共享 | 否 | 任意 | 高 |
路由元信息 | 静态配置、导航守卫 | 否 | 任意 | 中 |
优先使用 props
解耦:将路由参数转换为组件 props
,提高组件复用性。
复杂数据用状态管理:跨页面或全局数据使用 Pinia/Vuex 管理。
合理选择参数类型:路径参数用于标识资源,查询参数用于过滤、排序等。
避免过度依赖 URL 传参:对于敏感数据,考虑使用状态管理或 API 获取。
参数类型转换:路由参数默认是字符串类型,必要时手动转换。
动态路由参数变化时组件不刷新:使用 watch
监听路由变化。
刷新页面后数据丢失:使用本地存储、Cookie 或重新获取数据。
路由参数过多导致 URL 过长:考虑使用状态管理或 POST 请求。