Vue 3 With Vite
组件模板要有根节点
虽然 v3 不需要指定一个根节点,开发时很方便,但是会导致外部使用组件时没办法当成一个正常的 vnode 节点去使用。 导致诸如 class 等属性无法穿透至组件内部,因为 vue 无法知道 class 要作用在哪个节点上。 同时,控制台也会抛出提示:
[Vue warn]: Extraneous non-props attributes (calss) were passed to component but could not be automatically inherited because component renders fragment or text root nodes. 官方叫做 Attributes 继承。
Bad
// ComponentA
<template>
<div></div>
<div></div>
...
</template>
// App
<template>
<!-- 该 class 属性无效 -->
<ComponentA class="mt-2" />
</template>
Good
// ComponentA
<template>
<div>
<div></div>
<div></div>
...
</div>
</template>
// App
<template>
<!-- 该 class 属性可生效 -->
<ComponentA class="mt-2" />
</template>
当然,官方也有手动定义属性穿透的方法,可以看看稳定 总结,保持 v2 的良好习惯永远包一层根节点,一定没错。