Skip to content

Attribute

Attributes 继承

attributes 继承是 Vue 3 中的一个新特性,它允许组件的 attributes 属性被自动继承,指的是没有被组件声明为 propsemitsv-on 事件监听器的属性。例如 calssstyleid 等属性。

当一个组件以单个根元素的形式被渲染时,它的 attributes 属性会被自动继承到根元素上。这使得在组件中设置 attributes 属性更加方便和直观。

html
<!-- 子组件 MyComponent -->
<div>
  <button>click me</button>
</div>

父组件使用了该组件,传入 class属性:

vue
<!-- 父组件 -->
<MyComponent class="parent-class" />

DOM 渲染结果:

html
<div class="parent-class">
  <button>click me</button>
</div>

classstyle 的合并

如果父组件和子组件的根元素都设置了 classstyle 属性,那么它们的值会被合并。

html
<!-- 子组件 -->
<div class="btn" style="font-size: 12px">
  <button>click me</button>
</div>
vue
<!-- 父组件 -->
<MyComponent class="parent-class" style="color: red" />

DOM 渲染结果:

html
<div class="btn parent-class" style="font-size: 12px;color: red">
  <button>click me</button>
</div>

v-on 监听继承

v-on 监听事件也是同样的规则。

vue
<MyComponent @click="onClick" />

click 事件会被自动添加到 MyComponent 组件的根元素上,当根元素被点击时,会触发父组件的 onClick 方法。如果MyComponent 组件的根元素上也通过 v-on 绑定了一个事件监听器,则这个监听器和从父组件继承的监听器都会被触发。

禁用 Attributes 继承

如果不想组件自动继承 attributes,可以在组件的选项中设置 inheritAttrs: false

vue
<script>
export default {
  inheritAttrs: false,
};
</script>

从Vue 3.3 开始可以在 <script setup> 中使用 defineOptions :

vue
<script setup>
defineOptions({
  inheritAttrs: false,
});
</script>

禁用后我们可以使用 v-bind="$attrs" 将 attributes 绑定到你想要设置的元素上。

html
<div>
  <button v-bind="$attrs">click me</button>
</div>

<script setup> 中可以使用 useAttrs API来访问 attributes。

vue
<script setup>
import { useAttrs } from 'vue';
const attrs = useAttrs();
</script>

如果你显式的使用了 setup 函数而不是 <script setup> 标签,那么 attrs 会作为 setup() 对象的一个属性暴露:

vue
<script>
export default {
  setup(props, { attrs }) {
    return { attrs };
  },
};
</script>

多根节点的 Attributes 继承

多个根节点组件不会自动继承 attributes。如果 $attrs 没有被绑定,会抛出一个警告。

Released Under The MIT License.