Javascript Vue

Use Vue 3’s Fragment feature in Vue 2 to return multiple root elements2 min read

vue-frag

Use Vue 3’s Fragment feature in Vue 2 to return multiple root elements

<template>
<div v-frag> ⬅ This root element is unwrapped and removed on render!

<li>Element 1</li>
<li>Element 2</li>
<li>Element 3</li>
</div>
</template>

🌟 Features

✅ Multiple root nodes Without creating a functional component!
🔥 SSR Unwraps the root element on client-side post-hydration!
⚡️ Directives Supports v-if, v-for, and v-html!
👩‍🔬 Battle-tested Checkout the tests here!

🚀 Install

npm i vue-frag

🚦 Quick Setup

Register globally

Make it available anywhere in your Vue application.

import frag from ‘vue-frag’;
Vue.directive(‘frag’, frag);

Register locally

Explicitly register it to a component you want to use it in.

<script>
import frag from ‘vue-frag’;

export default {
directives: {
frag
},


};
</script>

Prefer a component API?

Create a Fragment.vue component:

<template>
<div v-frag>
<slot />
</div>
</template>

<script>
import frag from ‘vue-frag’;

export default {
directives: {
frag
}
};
</script>

And use it as a component:

<template>
<fragment>
No root element!
</fragment>
</template>

👨🏻‍🏫 Examples

Returning multiple root nodes

<template>
<div v-frag> <!– This element will be unwrapped –>

<div v-for=”i in 10″>
{{ i }}
</div>
</div>
</template>

Unwrapping the root node from a component

<template>
<div>
<!– Unwraps the root node of some-custom-component –>
<some-custom-component v-frag />
</div>
</template>

Supports v-if too

<template>
<div v-frag>
<template v-if />
</div>
</template>

Access fragment DOM nodes

<template>
<div v-frag>
Hello world
</div>
</template>

<script>
export default {
mounted() {
console.log(this.$el.frag)
}
}
</script>

Pin It on Pinterest

Generated by Feedzy