先简单引用官方的说法:“透传 attribute”指的是传递给一个组件,却没有被该组件声明为 props 或 emits 的 attribute 或者 v-on
事件监听器。最常见的例子就是 class
、style
和 id
。
下面直接上干货:
第一种情况(单个根节点):我们向子组件传递一个class类名,前提条件是子组件必须只有一个根节点,否侧无效。父组件透传过来的class类名,最终会渲染子组件的根节点。
代码如下:
//这是父组件的代码
<template>
<div>
<Test2 class="red" ></Test2> //给子组件传递一个类名
</div>
</template>
<style scoped lang="scss">
.red{
color: red;
}
</style>
//这是子组件的代码
<template>
<div> //这个盒子会自动接收到父组件透传过来的class类名
<div></div>
</div>
</template>
第二种情况(禁用 Attributes 继承):如果你不想让子组件自动继承父组件透传过来的东西,你可以在子组件选项中设置 inheritAttrs: false
。
代码如下:
//这是子组件的代码
<script setup >
defineOptions({
inheritAttrs: false
})
</script>
第三种情况(多个根节点):和单根节点组件有所不同,有着多个根节点的组件没有自动 attribute 透传行为。
代码如下:
//这是父组件的代码
<template>
<div>
<Test2 @click="print" :name="name"></Test2> //给子组件传递一些东西
</div>
</template>
//这是子组件的代码(方式一)
<template>
<div>
{{ $attrs.name }} //可以拿到透传过来的name值
</div>
<div @click="$attrs.onClick"> //可以触发透传过来的点击事件
</div>
<p v-bind="$attrs"> //可以拿到透传过来的所有东西
文本标签
</p>
</template>
//这是子组件的代码(方式二)
<template>
<div>
</div>
<button @click="getData"> //写一个点击事件来获取父组件透传过来数据及方法
子组件获取数据及方法
</button>
</template>
<script setup >
import { useAttrs } from 'vue';
const attrs = useAttrs()
const getData = () => {
attrs.onClick() //拿到父组件透传过来的点击事件
console.log(attrs) //拿到父组件透传过来的所有东西
}
</script>