这是我参与11月更文挑战的第4天,活动详情查看:2021最后一次更文挑战
记录 && 积累! 之前有几篇文章有作 Vue3学习总结的开始:
- Vue3-
defAsyncComponent异步组件(新增), - Vue3-
Suspense处理异步请求, - Vue3-
Teleport改变组件挂载的根节点, - Vue3-
computed & watch, - Vue3-
生命周期和setup()函数, - Vue3-初体验,
Vue3.x 官方文档 , 本文继续来学习: Vue3 的新特性之 fragments, 按官方文档翻译过来是 片段,
Vue3 新特新之 fragments: 
Vue 3 现在正式支持了多根节点的组件,也就是片段 fragments!
在 Vue2.x 中组件只有一个根节点,
我们知道Vue2.x 中组件只有一个根节点, 如果存在多个根节点就会报错, 在 Vue2.x 中组件模板 template 还要嵌套一个根节点, 如 <div>...</div>
/// src/components/Layout.vue
<template>
<div>
<header>这是一个组件 Header</header>
<main>这又是一个组件 Main...</main>
<footer>同样, 还可以有多个组件 Footer...</footer>
<my-component1>自定义组件1</my-component1>
<my-component2>自定义组2</my-component2>
</div>
</template>
在 Vue3.x 中可定义多个根节点:
这样就不用担心样式嵌套深层次的问题, 在 Vue2.x 版本中每个组件都要有一个根节点, 这样就多一个标签, 使得自定义组件多的话就多出很多不必要的标签元素.
在 Vue3.x 中,组件可以包含多个根节点!但是,这要求开发者显式定义 attribute 应该分布在哪里。
/// src/components/Layout.vue
<template>
<header>这是一个组件 Header</header>
<main v-bind="$attrs">这又是一个组件 Main</main>
<footer>同样, 还可以有多个组件 Footer...</footer>
<my-component1>自定义组件1</my-component1>
<my-component2>自定义组2</my-component2>
</template>