目录
一、路由传参概述
二、动态路由参数(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 中使用路由传递参数。
二、动态路由参数(params)
2.1 基础用法
动态路由参数通过在路由路径中定义 :参数名
来传递。参数将成为 URL 的一部分,适用于 SEO 或书签场景。
路由配置:
const routes = [{ path: '/user/:id', name: 'UserDetail', component: UserDetail },{ path: '/post/:id/:action?', name: 'Post', component: Post } // 可选参数
];
2.2 传递参数
通过路由链接或编程式导航传递参数。
<!-- 通过路由链接 -->
<router-link :to="{ name: 'UserDetail', params: { id: 123 } }">用户详情</router-link><!-- 通过编程式导航 -->
this.$router.push({ name: 'UserDetail', params: { id: 123 } });
2.3 获取参数
在目标组件中使用 useRoute
来获取路由参数。
<script setup>
import { useRoute } from 'vue-router';
const route = useRoute();
console.log(route.params.id); // 输出: 123
</script>
2.4 可选参数
通过在参数后添加 ?
标记,使其成为可选参数。
{ path: '/user/:id?', component: User }
2.5 多个参数与正则约束
可以使用正则表达式来约束参数格式,例如:
{ path: '/article/:id(\\d+)/:action(edit|view)', component: Article }
2.6 多 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 }
];
参数传递:
<router-link :to="{ name: 'ProductDetail', params: { category: 'electronics', id: 456 } }">电子产品详情</router-link>
获取参数:
<script setup>
import { useRoute } from 'vue-router';
const route = useRoute();
console.log(route.params.category); // electronics
console.log(route.params.id); // 456
</script>
结合 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
中传递多个可选参数:
<router-link :to="{ name: 'UserDetail', params: { id: '123' } }">用户详情</router-link>
<router-link :to="{ name: 'UserDetail', params: { id: '123', name: 'John' } }">用户详情</router-link>
获取可选参数
通过 useRoute()
获取传递的多个可选参数:
<script setup>
import { useRoute } from 'vue-router';
const route = useRoute();
const userId = route.params.id || 'defaultId'; // 提供默认值
const userName = route.params.name || 'defaultName'; // 提供默认值
console.log(userId); // 输出: "123" 或 "defaultId"
console.log(userName); // 输出: "John" 或 "defaultName"
</script>
三、查询参数(Query)
查询参数通过 URL 的查询字符串传递,适合传递可选参数、过滤条件等。
3.1 特点与应用场景
查询参数不会影响路由匹配,适合频繁变化的参数。
3.2 传递参数
通过路由链接:
<router-link :to="{ name: 'UserList', query: { page: 2, size: 10 } }">第二页</router-link>
通过编程式导航:
this.$router.push({ name: 'UserList', query: { page: 2, size: 10 } });
3.3 获取参数
<script setup>
import { useRoute } from 'vue-router';
const route = useRoute();
console.log(route.query.page); // 2
console.log(route.query.size); // 10
</script>
3.4 保留当前查询参数
通过 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 } }}
];
组件接收参数:
<!-- UserProfile.vue -->
<script setup>
const props = defineProps({ id: String });
</script><!-- UserSidebar.vue -->
<script setup>
const props = defineProps({ admin: Boolean });
</script>
五、props 解耦(推荐方式)
使用 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 })}
];
组件接收参数:
<script setup>
const props = defineProps({ id: String, query: String, page: Number });
</script>
六、状态管理(Pinia/Vuex)
对于复杂或跨页面的数据传递,推荐使用状态管理库。
6.1 使用 Pinia 示例
定义 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:
<script setup>
import { useUserStore } from '@/stores/user';
import { useRouter } from 'vue-router';const router = useRouter();
const userStore = useUserStore();const goToUser = (id) => {userStore.setUserId(id);router.push({ name: 'UserDetail' });
};
</script>
七、路由元信息(meta)
路由配置中可以添加元信息(meta
),例如权限控制、页面标题等。
路由配置:
const routes = [{ path: '/dashboard', name: 'Dashboard', component: Dashboard, meta: { requiresAuth: true, title: '控制面板' }}
];
获取元信息:
<script setup>
import { useRoute } from 'vue-router';
const route = useRoute();
console.log(route.meta.title); // "控制面板"
</script>
全局导航守卫中使用:
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 请求。