- Start Date: 2022-05-17
- Target Major Version: 3.x
- Reference Issues:
- Implementation PR:
Add fragment
built-in component that acts as a <template>
empty wrapper tag.
<template>
<WrapperComponent v-if="shouldWrap">
<img src="cat.jpg" alt="Cat" />
</WrapperComponent>
<img v-else src="cat.jpg" alt="Cat" />
</template>
<template>
<component :is="shouldWrap ? WrapperComponent : 'fragment'">
<img src="cat.jpg" alt="Cat" />
</component>
</template>
There are cases when some markup should be conditionally wrapped within a tag\component or not wrapped at all. Right now you have 2 options on how to deal with that: either duplicate the markup or extract that code into a separate component. Both are not ideal: duplicate code is invisibly coupled (changes in one copy should be reflected in all other copies), extracting into component is cumbersome. It gets more tedious when you have multiple of those cases in a single component.
You might also want to create your own kind of fragment
component. But it will recieve all the custom directives from the parent, which will result in errors.
Example:
<component :is="shouldWrap ? 'div' : 'MyFragmentComponent'" v-custom-directive>
<img src="cat.jpg" alt="Cat">
</component>
<component is="fragment">
should be compiled into h('fragment')
. Vue renderer should be updated accordingly to support rendering fragments that way.
<component is="fragment">foo</component>
should produce only foo
as a render result.
Custom directives applied to a fragment
component should be discarded.
Possibly a duplicate of <template>
tag functionality. See Unresolved questions section.
Another approach could be to add suppoort for null
or undefined
as the <component>
is
attribute.
This is not a breaking change. All the exisiting components that already define a Fragment
component should continue to function without any issues.
Should we allow for <fragment>
tag to work the same way?
Should it be <>
instead of <fragment>
?
Would that conflict with the <template>
tag?