Vue.js fragments

All manner of googling didn’t turn up a good result for this problem.

Sometimes, you need a wrapper component with logic attached that does not render to the UI.

For example, child components with a percentage of the parent can’t just have a div wrapped around them for conditional logic.

Another example (which I found a different, novel solution for) is using more than one child component in a root node. Only one renders, but a few are there and are excluded by logic.

React has a ‘fragment’ for this and afaik vue.js does not.

Using ‘vue-fragment’ adds a helpful fragment tag that is removed during render, but allows application of logic and generally acting as a ‘root’ component for multiple siblings.

below, we are using a ‘fragment’ tag to render or hide 2 items based on if the user is an admin. Trivially wrapping these in a div with logic breaks the layout.

                <b-navbar-nav>
                    <b-nav-item :to="'/'">
                        Dashboard
                    </b-nav-item>
                    <b-nav-item :to="'/something'">
                        Something
                    </b-nav-item>

                    <fragment v-if="user.role === 'Admin'">
                        <b-nav-item :to="'/item-1'">
                            Item 1
                        </b-nav-item>
                        <b-nav-item :to="'/item-2'">
                            Item 2
                        </b-nav-item>
                       
                    </fragment>
                </b-navbar-nav>

Install from yarn (or npm i vue-fragment)

yarn add vue-fragment

Add the fragment component

import { Plugin } from 'vue-fragment'
import Vue from 'vue'
Vue.use(Plugin)
<fragment>
  <div>Use the fragment! The fragment tag will be removed at render time.</div>
</fragment>