$attrs 可以收集父组件中的所有传过来的属性除了那些在组件中没有通过 props 定义的。
引申说明一下,如果组件的嵌套层级有点深但又不那么深,比如三层。
我们如果使用props的话,最里面的组件想要获取最外层组件的数据,就要通过中间的组件的props来传递,
但是这个props对于中间的这个组件没啥用处,它就是做了一个桥梁而已。我们平时写代码时候其实经常碰到
这种场景,写起来有时候觉得挺烦的。所以就有了这个$attrs来帮助我们,不必在中间组件中写props就可以让
最里面的组件拿到最外面组件传进来的数据。
那么,具体怎么使用呢?
看看下面的代码吧,很简单就懂了
准备三个组件

//grandfather
<template>
<div style="background: blue">
father in grandfather
<father :father-age="50" :child-time="`${time}`"></father>
</div>
</template>
<script>
import father from './father'
export default {
components: {
father
},
data () {
return {
time: new Date().getTime()
}
}
}
</script>
//father
<template>
<div style="background: red">
child in father
<div>
<span>father age:</span>{{fatherAge}}
</div>
<child v-bind="$attrs"></child>
</div>
</template>
<script>
import child from './child'
export default {
components: {
child
},
props: {
fatherAge: {
type: Number,
default: 0
}
}
}
</script>
//child<template>
<div style="background: green">
<div>child</div>
<div>time: {{childTime}}</div>
</div>
</template>
<script>
export default {
props: {
childTime: {
type: String,
default: ''
}
}
}
</script>需要从爷爷组件直接传给子组件的数据,不要在父组件中的props中声明。
在子组件上通过v-bind的方式就可以把父组件中未声明而子组件需要从爷爷组件中获取的数据传给子组件。
当然,子组件props肯定是要声明的,还是props的用法啦。
转载请注明:谷谷点程序 » vue中通过使用$attrs实现组件之间的数据传递功能