vue3透传 Attributes

发布时间 2023-06-27 11:30:20作者: 商品部-林军

image-20220827172052064

“透传 attribute”指的是传递给一个组件,却没有被该组件声明为 props 或 emits 的 attribute 或者 v-on 事件监听器。最常见的例子就是 classstyle 和 id

当一个组件以单个元素为根作渲染时,透传的 attribute 会自动被添加到根元素上

A组件:

<template>
  <h3>ComponentA</h3>
  <ComponentB class="component-b" />
</template>
<script>
import ComponentB from "./ComponentB.vue"
export default {
  components: {
    ComponentB
   }
}
</script>

B组件

<template>
  <h3>ComponentB</h3>
</template>
<style>
.component-b{
  color: red;
}
</style>

禁用 Attributes 继承

<template>
  <h3>ComponentB</h3>
</template>
<script>
export default {
  inheritAttrs:false
}
</script>
<style>
.component-b{
  color: red;
}
</style>