$attrs and Attributes inheritance in vue3
Official Documentation:/guide/components/#attribute-inheritance
First, let’s introduce what Attributes inheritance is, that is, attribute inheritance!
When a parent component binds properties to a child component (props attribute, class attribute, custom events, style attribute, etc.)
// Parent component<Demo @click="fn1" @getname="fn2" numm="111" :name="slotName" class="abc" > </Demo>
The root element of the child component (i.e. the outermost element) will be automatically inherited and removed.props
、emits
Outside attributes
These properties are encapsulated$attrs
On the object
// <template> <div> {{ $attrs }} </div> </template> <script setup> import { ref, useAttrs } from 'vue' const props = defineProps({ name: String }) let attrs = useAttrs() (attrs) </script>
attrs = Proxy {numm: ‘111’, class: ‘abc’, __vInternal: 1, onClick: ƒ, onGetname: ƒ}
$attrs:
this$attrs
Object contains except as declared by the componentprops
andemits
All other attributes except for, e.g.class
,style
,v-on
Listeners and so on.
Disable Attributes inheritance: Cancel the root node automatic inheritance
// An additional configuration is required<script> export default { inheritAttrs: false, } </script> <script setup> import { ref, useAttrs } from 'vue' const props = defineProps({ name: String }) ref(12) let attrs = useAttrs() (attrs) </script>
v-bind=$attrs
Implement the Attribute inheritance of the Sun component
We want all the transmissive attributes to be applied to the internal elements, not to the outer root node. We can set itinheritAttrs: false
and usev-bind="$attrs"
To achieve
<div class="btn-wrapper"> <button class="btn" v-bind="$attrs">click me</button> </div>
No parametersof
v-bind
All attributes of $attrs will be applied to the target element as attribute
This is the article about the inheritance of $attrs and Attributes in vue3. For more related content related to inheritance of $attrs and Attributes, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!