Vue3$Data-FallthroughAttributes

47 阅读1分钟

Vue3$Data-FallthroughAttributes

0. What is Fallthrough Attributes

组件可以显式声明接收父组件的 props 和 emit。组件没有声明但是父组件传入的 attributes 就是 fallthrough attributes。

Fallthrough attributes 的 key:

  • $attrs['foo-bar']
  • $attrs.onClick

默认情况:

  • single root element(单根节点组件):fallthrough attributes 自动加到根节点上
    • class & style & event:合并(比如根组件 class="a",fallthrough attributes 传入 class="b",最终的结果:class="a b"
    • style 冲突:以 fallthrough attributes 为主
    • event 顺序:先子后父
  • multiple roots element(多根节点组件):不会应用,没有处理的话有报警

应用场景:

  • 使用默认情况(单文件组件):对于 class、style 和 id这样的内容,我们不想要声明 props,但是想使用(自己使用 / 给子组件使用)
  • 不使用默认情况:我们想自己决定如何使用 fallthrough attributes
  • 使用 fallthrough attributes:无论是否使用默认情况,我们都可以在 template 和 script 中获取和使用 fallthrough attributes

1. 使用默认情况(单文件组件)

<!-- template of <MyButton> -->
<button>Click Me</button>
<MyButton class="large" />
<button class="large">Click Me</button>

2. 不使用默认情况(禁用 Attributes 继承)

defineOptions({
  inheritAttrs: false
})

3. 使用 fallthrough attributes

我们可以在 template 和 script 中使用传入的属性:

<span>Fallthrough attributes: {{ $attrs }}</span>
<div class="btn-wrapper">
  <button class="btn" v-bind="$attrs">Click Me</button>
</div>
<script setup>
import { useAttrs } from 'vue'

const attrs = useAttrs()
</script>