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 继承

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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cocoonne

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值