props核心作用是将URL参数自动转为组件props以实现解耦复用;支持布尔模式(映射params)、对象模式(传静态值)、函数模式(灵活处理params/query/类型转换)及命名视图单独配置。
路由配置里的 props 属性,核心作用是把 URL 中的参数“自动转成组件的 props”,让组件不再依赖 $route,从而真正实现解耦、复用和可测试。它不是可有可无的语法糖,而是 Vue Router 设计中提升组件独立性的关键机制。
当路由含动态段(如 /user/:id),设 props: true,Vue Router 会自动把 params 对象里的字段,按同名方式注入组件 props。
{ path: '/user/:id', component: User, props: true }
props: ['id'] 或 defineProps({ id: String })
params,不读取 query(即 ? 后面的参数)当你需要给组件塞一些与 URL 无关的静态信息,比如默认标题、开关状态或权限标识,就用对象写法。
{ path: '/admin', component: AdminPanel, props: { readOnly: false, title: '系统管理' } }
props: ['readOnly', 'title']
这是能力最强的方式,接收整个 $route 对象,返回一个纯对象,你可以自由组合、过滤、转换参数。
props: route => ({ id: Number(route.params.id), q: route.query.q })
props: ({ params, query }) => ({ id: params.id, keyword: query.q || '' }),清晰易维护如果路由用了多个命名视图(如 default 和 sidebar),props 不能全局设置,必须为每个视图单独指定策略。
{ path: '/user/:id', components: { default: UserProfile, sidebar: UserSidebar }, props: { default: true, sidebar: { showAvatar: true } } }
UserProfile 接收 id,UserSidebar 接收固定配置,互不影响