Vue.js Fragments without a plugin like React

Invisible container elements are a very useful thing. These are available in Vue and React ...

At work I program a lot with React and there I also use so-called Fragments. A fragment is a pseudo element, which can be used as a container to store HTML elements in there. In the code, this looks like this in React:

<React.Fragment>
    <ChildA />
    <ChildB />
    <ChildC />
</React.Fragment>

The special thing about this element, however, is that once it is rendered in the front end, you will not see this container.

Fragments in Vue.js

Of course, I wanted to have this feature in my Vue.js projects as well and looked for an alternative for vue.

In the end I came across a very simple solution for Vue.js. Templates.

When you put your elements into a template container, it does exactly the same thing as the fragments in React. This looks like this in code:

<template v-for="(foo, index) in bar">
	<span v-if="foo.baz">My Custom Content</span>
	<p>{{ foo.text }}</p>
</template>

The above code performs the same task as the React fragments and is even more flexible, allowing inline attributes such as v-for and v-if. When the code is rendered, the template container is not visible in the frontend.

If you realize a project with Vue.js, you should definitely keep this function in mind. It will be very useful to you.

Topics

HTML Javascript Program react Tips Vue.js

Beitrag teilen

WhatsApp it