vue多层传递$attrs
解释:一个组件嵌套了子组件,子组件又嵌套了子组件,而且在父组件里需要自定义的属性很多,传递给子组件的数据很多,但是并不是每一个组件都会用到所以新增一个$attrs这个属性
官方文档说明:
解释:包含了父作用域中不作为 prop 被识别 (且获取) 的特性绑定 (class 和 style 除外)。 意思就是父组件往子组件传没有在props里声明过的值时,子组件可以通过$attrs接受,且只包含父组件没有在props里声明的值。
父组件
<template>
<div class="home">
<child gender="child" age="22"/>
</div>
</template>
<script>
import Child from '../components/Child'
export default {
name: 'home',
components: {
Child,
}
</script>
子组件
<template>
<div>
Child
<br>
<span>gender: {{$attrs['gender']}}</span>
<br>
<span>age: {{$attrs['age']}}</span>
<br>
</div>
</template>
<script>
export default {
name: 'Child'
}