Featured image of post Understanding Fragment in Vue3

Understanding Fragment in Vue3

I wonder if anyone has encountered the following error information in Vue2:

1
2
Errors compiling template:
Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.

This is an error prompt thrown by Vue2. It means that a component can only have one root element. When we create a new Vue page, there are usually multiple different element nodes. We will wrap a div at the outermost layer to make it the root node of this page. But this is not user-friendly. Sometimes we don’t need this div element.

Vue3 has solved this problem. Vue3 has introduced a new DOM-like tag element <Fragment></Fragment>. If there are multiple element nodes in the Vue page, Vue will add a <Fragment></Fragment> tag to these element nodes during compilation. And this tag does not appear in the DOM tree.

Example

1
2
3
4
5
<template>
 <header>...</header>
 <main v-bind="$attrs">...</main>
 <footer>...</footer>
</template>