Vue Router 路由组件传参
路由组件传参
将props传递给路由组件
除了使用this.$route.params.xxx获取动态段以外(限制组件灵活性,只能用于特定URL),还可以通过props来获取,从而将组件和路由解耦,取代与$route的耦合(耦合是指获params或query等一些属性,必须通过$route来获取):
<template>
<div>User组件:{{id}}</div>
</template>
<script>
export default {
name: "About",
props:['id']
}
</script>
{
path: '/about/:id',
name: 'About',
component: () => import('@/views/About'),
props: true
}
布尔模式
当props设置为true时,this.$route.params将被设置为组件的props,可以在组件中通过定义props:['xxx']来接收。
命名视图
对于有命名视图的路由(components:{default:xxx,xxx:xxx}),必须为每个命名视图定义props配置:
{
path: '/settings',
components: UserSettings,
children: [
{
path: 'emails',
component: UserEmailsSubscriptions
},
{
path: 'profile/:id',
components: {
default: UserProfile,
helper: UserProfilePreview
},
props: {
default: true,
helper: false
}
}
]
}
即对于components中有default视图以及命名视图的路由,必须为命名视图定义props配置:
{
path: '/:id',
components: {
default: () => import('@/views/Home'),
about: () => import('@/views/About')
},
props: {
default: true,
about: true
}
}
因为同一path会跳转到不同组件,而不同组件需不需要props传参有自己的要求,所以要为每个命名视图都进行props配置(包括default)。
对象模式
当props是一个对象时,将原样设置为组件props,当props是静态的时候很有用。
<template>
<div id="app">
<div>{{ newValue }}</div>
</div>
</template>
<script>
export default {
name: "Home",
props: ['newValue']
}
{
path: '/:id',
component: () => import('@/views/Home'),
props: {
newValue: false
}
}
函数模式
props参数为一个函数。
例如请求路径为'/search?q=vue',映射路由后,对应Home组件,并且将{query:'vue'}(这里的query是根据路由props中的query来的,在组件的props中也将用query来代表key)作为props传给Home。
箭头函数 加括号的函数体返回对象字面量表达式。
<template>
<div id="app">
<div>{{ query }}</div>
</div>
</template>
<script>
export default {
name: "Home",
props: ['query']
}
{
path: '/',
component: () => import('@/views/Home'),
props: route => ({
query: route.query.q
})
}
请尽可能保持props函数为无状态的,因为它只会在路由发生变化时起作用。
如果需要状态来定义props,请使用包装组件,这样vue才可以对状态变化做出反应。