What is Fragment and what can it do? #11642
-
In the source code of It also seems to be used to wrap some sub-components. So what is the difference between it and template? I also discovered some strange behaviors. <template>
<div class="draft-page">
<Fragment>
<p>I will not be rendered on the page</p>
</Fragment>
<component :is="Fragment">
<p>I won't be rendered to the page either</p>
</component>
<component :is="vnode" />
<component :is="jsx" />
<component :is="MyFragment">
<p>I will also be rendered on the page</p>
</component>
</div>
</template>
<script lang="tsx" setup>
import { h, Fragment, FunctionalComponent } from 'vue'
const vnode = h(Fragment, null, [
h('p', null, ['I will be rendered on the page']),
])
const jsx = (
// @ts-expect-error Type '{ $children: Element; }' does not have the same properties as type 'IntrinsicAttributes & VNodeProps'
<Fragment>
<p>TS complains, but I get rendered to the page</p>
</Fragment>
)
const MyFragment: FunctionalComponent = (_, { slots }) => (
// @ts-expect-error Type '{ $children: Element; }' does not have the same properties as type 'IntrinsicAttributes & VNodeProps'
<Fragment>{slots.default?.()}</Fragment>
)
</script> Why using Fragment directly in template and component doesn't work? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
A Fragment is not a real component. it's a Symbol representing a special kind of vnode. Fragments wrap dynamic lists of elements, typically created with v-for or by using a slot in a template. It's not meant to be used by developers in templates because the compiler inserts them where it makes sense anyway. |
Beta Was this translation helpful? Give feedback.
Yes it does.
They work in JSX/render functions by accident, I'd say.