Vue 2 Fragment Directive

1.4.3 · active · verified Sun Apr 19

vue-frag provides Vue 3's native fragment functionality to Vue 2 applications, allowing components to render multiple root elements without an artificial wrapper div. This addresses a core limitation in Vue 2's template syntax. The current stable version is 1.4.3. Releases are made on an as-needed basis, primarily for bug fixes and minor enhancements related to Vue 2 compatibility. Key differentiators include support for server-side rendering (SSR), compatibility with core Vue directives like `v-if`, `v-for`, and `v-html`, and offering both a Component API (`<fragment>`) and a Directive API (`v-frag`) for flexible usage. It can also be paired with `vue-frag-plugin` for automatic fragment injection, simplifying development by allowing multiple root nodes directly in SFCs.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates using the `Fragment` component to allow multiple root `<li>` and `<div>` elements within a Vue 2 component's template, which would otherwise require a single wrapper element.

<template>
    <fragment>
        <!-- This root element will not exist in the DOM, allowing multiple siblings -->
        <li>Element 1</li>
        <li>Element 2</li>
        <li v-if="showThirdElement">Element 3 conditionally rendered</li>
        <div v-for="item in items" :key="item.id">
            Item: {{ item.name }}
        </div>
    </fragment>
</template>

<script lang="ts">
import { Fragment } from 'vue-frag';
import Vue from 'vue';

export default Vue.extend({
    components: {
        Fragment
    },
    data() {
        return {
            showThirdElement: true,
            items: [
                { id: 1, name: 'Apple' },
                { id: 2, name: 'Banana' }
            ]
        };
    }
});
</script>

view raw JSON →