近期编写vue组件,用到vue新增的api$attrs和$listeners,看了网上很多帖子,感觉介绍的都不直观,并不能让使用者快速了解二者到底是什么作用,本文结合实际使用场景,给出$attrs和$listeners的使用方法。并且引入引深思考,和react props传递进行对比。
首先介绍$attrs
作用:主要用于跨组件传输props,中间组件使用v-bind = "$attrs"转发,具体有以下两点
1,接收为在props中定义的额外的props
created(){
console.log(this.$attrs)//打印出父组件传递的props
},
props:{
props1:{} //由于这里指明接受了props1属性,this.$attrs不再包括props1
}
说明:1,this.$attrs是父组件传递的props属性,但是在当前的组件,props中指明了的属性,this.$attrs不再包含
2,this.$attrs不包括class, style
2,传递props,实现props属性跨组件传递
//代码仅作为演示
<ComponentA
name = "我是根组件"
>
</ComponentA>
//A组件中使用了B组件
<template>
<ComponentB
v-bind = "$attrs"
>
</ComponentB>
</template>
//B组件中使用了C组件
<template>
<ComponentC
>
<div>{{$attrs.name}}</div>
</ComponentC>
</template>
2,inheritAttrs的作用
网上很多帖子把inheritAttrs和$attrs一块讲,其实二者没有关系,设置inheritAttrs为treu或者false对this.$attrs没有影响
1, inheritAttrs: false
当前组件未被注册使用的属性不会作为普通和html属性渲染
2,inheritAttrs: true
当前组件未被注册使用的属性会作为普通和html属性渲染
设置inheritAttrs false的意义在于是的属性的传输不至于模糊混乱,只渲染用到的属性
3,$listeners
场景:和$attrs类似,主要是从根组件向下传递事件,可以跨组件传递
//代码仅作为演示
<ComponentA
name = "我是根组件"
@click = 'componentAClick'
>
</ComponentA>
//A组件中使用了B组件
<template>
<ComponentB
v-bind = "$attrs"
v-on = "$listeners"
>
</ComponentB>
</template>
//B组件中使用了C组件
<template>
<ComponentC
>
<div>{{$attrs.name}}</div>
<button
@click="$listeners.click"
></button>
</ComponentC>
</template>
4,和react props的对比
在react中传递props,如果一层一层传递,只需要使用 <Component {...props}></Component>
在vue中相当于把属性和事件做了区分:
属性使用$attrs向下传递
事件使用$listeners向下传递
总结:对于vue的$attrs,$listeners主要用于跨组件属性和事件的传递,相当于在组件中加了一层数据model的转发,类似于react的{...props}
有更好的欢迎交流