How to use $attrs and $listeners in Vue
This article mainly explains "how to use $attrs and $listeners in Vue". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor learn how to use $attrs and $listeners in Vue.
Introduction
$attrs
Inherits all parent component properties (properties that are not received through props also include class class names and style styles).
InheritAttrs:
Whether the non-props attribute is displayed on the outermost layer of the tag, the default value is true, which inherits all parent component attributes (except for props specific bindings) as normal HTML attributes applied to the root element of the child component. If you do not want the component root element to inherit the attribute, set inheritAttrs: false, but class will still inherit.
$listeners
It is an object that receives all method bindings, contains all listeners acting on this component, and points all event listeners to a particular child element of this component in conjunction with vColon = "$listeners".
Give an example
In the parent component
Import Son from ". / components/son.vue"; export default {name: "App", components: {Son,},}
In the subcomponent
Import Son from ". / components/son.vue"; export default {name: "App", components: {Son,},}
As you can see, when inheritAttrs defaults to false, the attribute is passed to the outermost layer of the subcomponent
When inheritAttrs is true
When you use props to receive properties, the properties are not displayed
Summary: the attributes passed on the component tag will go to the outermost layer of the subcomponent tag if the subcomponent does not receive it.
Non-props attributes can receive {attribute name: attribute value} through $attrs
Export default {inheritAttrs: false,}; .img {width: 100px; height: 100px;}
When a click event is bound to a subcomponent, the click event is not triggered and can be successfully bound using the .native modifier.
Or bind to receive all methods through $listeners
Within the subcomponent
Result
At this point, I believe you have a deeper understanding of "how to use $attrs and $listeners in Vue". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!