很多时候,我们会写一些嵌套组件,比如A的子组件是B,B的子组件是C。这个时候如果A传递props给B,B又得传递props给C,我们经常在B传给C的时候这么写:
<template>
<child-component :someprop1="someprop1"
:someprop2="someprop2"
:someprop3="someprop3"
:someprop4="someprop4"
...
/>
</template>
这样写是很不优雅的,其实你可以直接用v-bind: $props
template>
<child-component v-bind="$props"/>
</template>
这里我们利用v-bind可以传递一个对象所有的property,类似于v-bind=“Obj”。例如,对于一个给定的post
post: {
id: 1,
title: 'My Journey with Vue'
}
下面的模板:
<blog-post v-bind="post"></blog-post>
等价于:
<blog-post
v-bind:id="post.id"
v-bind:title="post.title"
></blog-post>
这个配合 v-bind="$attrs" 在封装一些组件的时候非常有用,比如实现属性透传。
vm.
a
t
t
r
s
包
含
了
父
作
用
域
中
不
作
为
p
r
o
p
被
识
别
(
且
获
取
)
的
a
t
t
r
i
b
u
t
e
绑
定
(
c
l
a
s
s
和
s
t
y
l
e
除
外
)
。
当
一
个
组
件
没
有
声
明
任
何
p
r
o
p
时
,
这
里
会
包
含
所
有
父
作
用
域
的
绑
定
(
c
l
a
s
s
和
s
t
y
l
e
除
外
)
,
并
且
可
以
通
过
v
−
b
i
n
d
=
"
attrs 包含了父作用域中不作为 prop 被识别 (且获取) 的 attribute 绑定 (class 和 style 除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (class 和 style 除外),并且可以通过 v-bind="
attrs包含了父作用域中不作为prop被识别(且获取)的attribute绑定(class和style除外)。当一个组件没有声明任何prop时,这里会包含所有父作用域的绑定(class和style除外),并且可以通过v−bind="attrs" 传入内部组件——在创建高级别的组件时非常有用。
比如将上面传递进来的 props 全部绑定到 el-input 中,我们可以在子组件中这么写:
<template>
<div>
<el-input v-bind="$attrs" ></el-input>
</div>
</template>
2.二个components接受同样的props
<template>
<child-component v-bind="$props"/>
</template>
<script>
import ChildComponent from '@/components/ChildComponent'
export default {
props:{
someProp1: String,
someProp2: String,
someProp3: String,
// and so on
}
}
</script>
但这样有个问题,就是 C 组件修改了 props,那么 B 组件得一起修改,这样做的一个坏处有可能会有遗漏。另外就是代码冗余,看起来不精简。其实我们可以在 B 组件中这么写
<template>
<child-component v-bind="$props"/>
</template>
<script>
import ChildComponent from '@/components/ChildComponent'
export default {
props:{
...ChildComponent.options.props
}
}
</script>