vue3中的 $attrs 与 Attributes 继承

vue3中的 $attrs 与 Attributes 继承

官方文档:https://cn.vuejs.org/guide/components/attrs.html#attribute-inheritance

首先介绍一下什么是 Attributes 继承,即属性继承!

当一个父组件给子组件绑定属性时(props属性、class属性、自定义事件、style属性等等)

// 父组件
<Demo
    @click="fn1"
    @getname="fn2"
    numm="111"
    :name="slotName"
    class="abc"
>
</Demo>

子组件的根元素(即最外层的元素)会自动继承除去 propsemits 之外的属性

而这些属性都被封装到了 $attrs 对象上

// demo.vue
<template>
    <div>
        {
   
   { $attrs }}
    </div>
</template>

<script setup>
import { ref, useAttrs } from 'vue'

const props = defineProps({
    name: String
})

let attrs = useAttrs()
console.log(attrs)
</script>

attrs = Proxy {numm: ‘111’, class: ‘abc’, __vInternal: 1, onClick: ƒ, onGetname: ƒ}

$attrs:

这个 $attrs 对象包含了除组件所声明的 propsemits 之外的所有其他 attribute,例如 classstylev-on 监听器等等。

禁用 Attributes 继承:取消根节点自动继承

// 需要额外加上一个配置
<script>
export default {
    inheritAttrs: false,
}
</script>

<script setup>
import { ref, useAttrs } from 'vue'

const props = defineProps({
    name: String
})
 ref(12)
let attrs = useAttrs()
console.log(attrs)
</script>

v-bind=$attrs

实现孙组件的 Attribute 继承

扫描二维码关注公众号,回复: 15260211 查看本文章

我们想要所有的透传 attribute 都应用在内部的元素中, 而不是外层的根节点上。我们可以通过设定 inheritAttrs: false 和使用 v-bind="$attrs" 来实现

<div class="btn-wrapper">
  <button class="btn" v-bind="$attrs">click me</button>
</div>

没有参数的 v-bind 会将 $attrs 的所有属性都作为 attribute 应用到目标元素上

猜你喜欢

转载自blog.csdn.net/m0_63907100/article/details/129712157