You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Composition API获取Vue Router自定义props?

解决Vue Router传递静态Props的问题

你遇到的undefined和TypeScript警告,核心原因是组件未显式声明要接收的crumbs props,Vue Router的对象模式props确实可以传递静态值,但组件必须明确声明对应的props才能正确获取。另外,路由params为空是正常的,因为对象模式的props和URL参数无关。

正确使用props对象模式的步骤

1. 在组件中声明props(含TypeScript类型)

不管是Options API还是Composition API,都需要先在组件里定义要接收的props:

<script setup lang="ts">
import { toRef, onMounted } from 'vue'

// 声明props并定义类型
const props = defineProps<{
  crumbs: Array<{ label: string }>
}>()

const crumbs = toRef(props, 'crumbs')

onMounted(() => {
  console.log(crumbs.value) // 此时能正确拿到路由配置中传递的crumbs
})
</script>

如果是不用TypeScript的场景:

<script setup>
import { toRef, onMounted } from 'vue'

const props = defineProps({
  crumbs: {
    type: Array,
    required: true
  }
})

const crumbs = toRef(props, 'crumbs')

onMounted(() => {
  console.log(crumbs.value)
})
</script>

2. 保持你的路由配置不变

你的路由配置本身是正确的,不需要修改:

routes: [
  {
    path: '/map',
    name: 'map',
    component: () => import('../pages/MapPage.vue'),
    children: [
      { path: 'xxx', component: XXXMap, props: { crumbs: [{ label: 'XXX 多语言名称' }] } },
      { path: 'yyy', component: YYYMap, props: { crumbs: [{ label: 'YYY 多语言名称' }] } },
      { path: 'zzz', component: ZZZMap, props: { crumbs: [{ label: 'ZZZ 多语言名称' }] } },
      // ...
    ]
  }
]

关于使用meta属性的补充

你提到用meta属性可以正常工作,这确实是另一种传递静态路由元数据的方式,适合不需要作为组件props传递,而是需要在路由守卫、模板中直接访问的场景:

路由配置(添加meta)

routes: [
  {
    path: '/map',
    name: 'map',
    component: () => import('../pages/MapPage.vue'),
    children: [
      { path: 'xxx', component: XXXMap, meta: { crumbs: [{ label: 'XXX 多语言名称' }] } },
      // ...
    ]
  }
]

在

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 13:50:22