Vue透传 Attributes(详细解析)2
多根节点的 Attributes 继承:必须显式绑定
单根节点组件有默认的透传行为,但多根节点组件没有自动透传机制。若组件有多个根节点且未显式绑定 $attrs
,Vue 会抛出运行时警告(因无法确定透传到哪个根节点)。
示例:未显式绑定导致警告
假设 <CustomLayout>
是一个多根节点组件:
<!-- <CustomLayout> 的模板(多根节点,未绑定 $attrs) --><template><header>头部</header><main>主体</main><footer>底部</footer></template>
父组件使用时传入透传属性:
<!-- 父组件模板 --><template><CustomLayout id="custom-layout" @click="changeValue" /></template>
此时 Vue 会抛出警告:[Vue warn]: Component is missing attribute fallthrough because it has multiple root nodes.
(组件有多个根