Appearance
路由组件传参
在你的组件中使用 $route
或 useRoute()
会与路由紧密耦合,这限制了组件的灵活性,因为它只能用于特定的 URL。我们可以通过 props
配置来解除这种行为。
我们可以通过设置 props: true
来配置路由将 id
参数作为 prop 传递给组件:
js
const routes = [
{ path: '/user/:id', component: User, props: true }
]
通过声明 prop 来在 User.vue
中删除对 $route
的直接依赖:
vue
<!-- User.vue -->
<script setup>
defineProps({
id: String
})
</script>
<template>
<div>
User {{ id }}
</div>
</template>
布尔模式
当 props
设置为 true
时,route.params
将被设置为组件的 props。
命名视图
对于有命名视图的路由,你必须为每个命名视图定义 props
配置:
js
const routes = [
{
path: '/user/:id',
components: { default: User, sidebar: Sidebar },
props: { default: true, sidebar: false }
}
]
对象模式
当 props
是一个对象时,它将原样设置为组件 props。当 props 是静态的时候很有用。
js
const routes = [
{
path: '/promotion/from-newsletter',
component: Promotion,
props: { newsletterPopup: false }
}
]
函数模式
js
const routes = [
{
path: '/search',
component: SearchUser,
props: route => ({ query: route.query.q })
}
]
URL /search?q=vue
将传递 {query: 'vue'}
作为 props 传给 SearchUser
组件。
通过RouterView
你还可以通过 <RouterView>
插槽 传递任意参数:
vue
<RouterView v-slot="{ Component }">
<component
:is="Component"
view-prop="value"
/>
</RouterView>
在这种情况下,所有视图组件都会接收到 view-prop
。