vue3中的 $attrs 与 Attributes 继承
作者:cocoonne
这篇文章主要介绍了vue3中的 $attrs 与 Attributes 继承的相关资料,首先介绍了什么是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>子组件的根元素(即最外层的元素)会自动继承除去 props、emits 之外的属性
而这些属性都被封装到了 $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 对象包含了除组件所声明的 props 和 emits 之外的所有其他 attribute,例如 class,style,v-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 应用到目标元素上
到此这篇关于vue3中的 $attrs 与 Attributes 继承的文章就介绍到这了,更多相关vue3 $attrs 与 Attributes 继承内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
