组件传值$attrs
vue中向子级组件传值,最常用到的还是v-bind:param="obj",子级组件通过props属性接收。但是当值需要传递很多层时,props传值就显得过于麻烦。这个时候就可以使用$attrs向下传值。用法如下:总结:
- $attrs中保存的是父组件通过v-bind指令传下来的值,这些值不包含props接收的值。
- 通过data属性直接接收 $attrs 中得值,不会影响 $attrs中值的向下传递。
- $attrs中仅包含父级组件向下传递的值,即通过v-bind指令传递的数据。
- 假如B组件没有设置v-bin="$attrs",那么在C组件中,this. $attrs中将不会有A组件传递下来的数据。
//假设ABC三个组件
//A.vue
<template>
<div style="background-color:#bbffff;width:400px;height:100px;">
<bcomponent :b="message" :b1="param"></bcomponent>
</div>
</template>
<script>
import bcomponent from './B'
export default {
inheritAttrs:false,
components:{
bcomponent
},
data(){
return {
message:"A组件",
param:{
student:{
name:"小明",
age:"20",
gender:"男"
},
class:{
level:"初一",
teacher:"小红"
}
}
}
}
}
</script>
//B组件
<template>
<div>
<p>B组件props接收:{{b}}</p>
<p>B组件通过data属性接收$attrs的值:{{param}}</p>
<p>B组件$attrs接收:{{$attrs}}</p>
<c_component v-bind="$attrs"></c_component>
</div>
</template>
<script>
import c_component from '../views/C'
export default {
components:{
c_component
},
props:{
b:{
type:String
}
},
data:function(){
return {
param:this.$attrs
}
}
}
</script>
//C组件
<template>
<p>C组件$attrs:{{$attrs}}</p>
</template>
<script>
export default {
}
</script>
渲染后样式:
数据在标签渲染里控制inheritAttrs
简单来说,inheritAttrs属性,控制的是父组件通过v-bind向子组件传的数据,如果子组件没有props接收,那么这些值是否在子组件的html标签中显示出来。最直观的作用,就是组件被调用时,并且与子组件有相同的属性,设置inheritAttrs:false可以有效防止,组件自身的属性被覆盖。这句话没看懂不要紧,看下面的案例就懂了。
继续借用上面ABC三个组件的案例来展示。在默认情况下,inheritAttrs:true,当前组件没有通过props接收父组件的数据,就会渲染到标签中。
当我在B组件中添加inheritAttrs:flase属性时,效果如图。由图中可以看出,B组件的div标签中并没有渲染出没有接收的数据。