• Stars
    star
    194
  • Rank 194,042 (Top 4 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 3 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🤲 Create Fragments (multiple root-elements) in Vue 2

vue-frag

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

<template>
    <Fragment> ⬅ This root element will not exist in the DOM

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

<script>
import { Fragment } from 'vue-frag'

export default {
    components: {
        Fragment
    }
}
</script>

👉 Try it out on CodePen!

🔥 Pro-tip

Want to be able to just have multiple root-nodes in your SFC without a wrapper? Use vue-frag-plugin to automatically inject vue-frag so that you can return multiple root nodes without a fragment component!

Support this project by ⭐️ starring and sharing it. Follow me to see what other cool projects I'm working on! ❤️

🌟 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

You can either choose to use the Component or Directive API.

Component API

The Component API is designed to be used at the root of the template. It should feel intuitive to use and cover most use-cases.

Import Fragment and use it as the root element of your component:

<template>
    <Fragment>
        Hello world!
    </Fragment>
</template>

<script>
import { Fragment } from 'vue-frag'

export default {
    components: {
        Fragment
    }
}
</script>

Register globally

Globally registering the component lets you use it without needing to import it every time.

import { Fragment } from 'vue-frag'

Vue.component('Fragment', Fragment)

Directive API

Use the Directive API to have more nuanced control over placement. For example, if you want to unwrap the root node of a component on the usage-end.

The Component API uses the Directive API under the hood.

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

<script>
import frag from 'vue-frag'

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

Register globally

Make it available anywhere in your Vue application.

import frag from 'vue-frag'

Vue.directive('frag', frag)

👨🏻‍🏫 Examples

Returning multiple root nodes

Component API

<template>
    <Fragment> <!-- This element will be unwrapped -->

        <div v-for="i in 10">
            {{ i }}
        </div>
    </Fragment>
</template>

Directive API

<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

Use the Directive API to unwrap the root node of a component.

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

Supports v-if too

<template>
    <div v-frag>
        <template v-if="isShown">
            Hello world!
        </template>
    </div>
</template>

Access fragment DOM nodes

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

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

💁‍♀️ FAQ

When would I want to return multiple root nodes?

Whenever you feel like the root-element of your component adds no value and is unnecessary, or is messing up your HTML output. This usually happens when you want to return a list of elements like <li>List Items</li> or <tr><td>Table Rows</td></tr> but you have to wrap it in a <div>.

In Vue 2, it's possible to return multiple nodes with a Functional Component but functional components are stateless (no data() or life-cycle hooks), doesn't support methods, doesn't have very good template support, and can lead to SSR bugs (eg. mismatching nodes).

Related VueJS Issues / Stackoverflow Qs:

How does this work?

vue-frag works by tricking Vue.js to think that the root element is still in the DOM, when it's actually not.

When vue-frag is applied to an element, it uses the inserted directive hook to swap the element out with its children to remove itself from the DOM. It then patches surrounding DOM nodes (eg. parent, sibling, children) to make them think that the element is still in the DOM.

Here are all the DOM APIs Vue.js uses that are patched:

Does v-show work?

Like in Vue 3, v-show does not work on components that return a fragment. v-show works by setting style="display: none" on the root element of the target component. With vue-frag removing the root element, there would be no grouping-element to apply the display: none to. If the fragment returned elements, it's possible to apply it to each child-node, but it's possible for them to be text-nodes which cannot be styled.

👨‍👩‍👧 Related

  • vue-frag-plugin - Build-time plugin to seamlessly use multiple root nodes
  • vue-subslot - 💍 pick out specific elements from component <slot>s
  • vue-vnode-syringe - 🧬 Add attributes and event-listeners to <slot> content 💉
  • vue-proxi - 💠 Tiny proxy component
  • vue-pseudo-window - 🖼 Declaratively interface window/document in your Vue template
  • vue-v - render vNodes via component template

More Repositories

1

tasuku

✅ タスク — The minimal task runner for Node.js
TypeScript
1,687
star
2

minification-benchmarks

🏃‍♂️🏃‍♀️🏃 JS minification benchmarks: babel-minify, esbuild, terser, uglify-js, swc, google closure compiler, tdewolff/minify
TypeScript
830
star
3

cleye

👁‍🗨 cleye — The intuitive & typed CLI development tool for Node.js
TypeScript
361
star
4

snap-tweet

Snap a screenshot of a tweet 📸
TypeScript
312
star
5

vue-2-3

↔️ Interop Vue 2 components in Vue 3 apps and vice versa
JavaScript
277
star
6

pkgroll

📦 🍣 Next-gen package bundler for TypeScript & ESM
TypeScript
249
star
7

ts-runtime-comparison

Comparison of Node.js TypeScript runtimes
TypeScript
219
star
8

link

🔗 A better `npm link`
TypeScript
117
star
9

type-flag

⛳️ Typed command-line arguments parser for Node.js
TypeScript
114
star
10

get-tsconfig

tsconfig.json paser & paths matcher
TypeScript
91
star
11

github-cdn

🛰 Github CDN Server
JavaScript
47
star
12

ci

Run npm ci using the appropriate Node package manager (npm, yarn, pnpm)
TypeScript
45
star
13

dbgr

Lightweight debugger for Node.js
TypeScript
44
star
14

clean-pkg-json

Script to remove unnecessary properties from package.json on prepublish hook
TypeScript
41
star
15

vue-frag-plugin

Webpack/Rollup/Vite plugin to add multiple root-node support to Vue 2 SFCs
TypeScript
41
star
16

instant-mocha

☕️ Build tests with Webpack and run with Mocha in one command
TypeScript
41
star
17

resolve-pkg-maps

Resolve package.json `exports` & `imports` maps
TypeScript
39
star
18

git-publish

☁️ Publish your npm package to a GitHub repository branch
TypeScript
38
star
19

compare-bun-node

Comparison of Bun's API against Node.js's
JavaScript
38
star
20

VisualQuery

Light & minimal front-end query builder for jQuery
JavaScript
38
star
21

webpack-localize-assets-plugin

🌐 Localize your Webpack bundle with multiple locales
TypeScript
38
star
22

webpack-json-access-optimizer

Webpack plugin to tree-shake and minify JSON modules
TypeScript
37
star
23

terminal-columns

Render readable & responsive tables in the terminal
TypeScript
32
star
24

deps

📦🔍 Analyze which package.json dependencies are in-use with V8 Coverage 🔥
TypeScript
31
star
25

vue-pseudo-window

🖼 Declaratively interface window/document/body in your Vue template
JavaScript
31
star
26

manten

💮 満点 - Lightweight testing library for Node.js
TypeScript
29
star
27

svg-browser-export

Export SVG to PNG, JPEG, or WEBP in the browser
TypeScript
23
star
28

comment-mark

Interpolate strings with HTML comment markers!
TypeScript
23
star
29

npm-multi-publish

Publish an npm package to multiple registries
JavaScript
23
star
30

reactive-json-file

💎 Reactively sync JSON mutations to disk
TypeScript
23
star
31

playwright-start

Start a long-running Playwright browser server via CLI
TypeScript
22
star
32

ink-task-list

Task runner components for Ink
TypeScript
22
star
33

chainset

Set object values using property chaining syntax
TypeScript
21
star
34

build-this-branch

🤖 Script to automate creating built branches
TypeScript
21
star
35

vue-vnode-syringe

🧬 Add attributes and event-listeners to <slot> content 💉
JavaScript
20
star
36

vue-dom-hints

Vue.js devtool for identifying Vue components and their SFC paths in the DOM
JavaScript
20
star
37

vue-grep

Grep your Vue.js codebase with CSS selectors
TypeScript
19
star
38

git-squash-branch

Script to squash the commits in the current Git branch
TypeScript
17
star
39

fs-fixture

Easily create test fixtures at a temporary file-system path
TypeScript
16
star
40

vue-split-view

Create a resizable split-view to partition the UI
Vue
16
star
41

alias-imports

Create Node.js aliases via imports map
TypeScript
16
star
42

vue-import-loader

🌐 Webpack loader to automatically detect & import used components
JavaScript
13
star
43

fs-require

Create a require() function from any file-system. Great for in-memory fs testing!
TypeScript
13
star
44

pkg-entry-points

Get all entry-points for an npm package. Supports the `exports` field in `package.json`
TypeScript
13
star
45

vue-subslot

💍 Pick out specific elements from the component <slot>
JavaScript
12
star
46

gh-emojis

Use GitHub emojis from their API as an npm package
JavaScript
12
star
47

litemark

🖋 GitHub Flavored Markdown Editor
Vue
12
star
48

hirok.io

👤 My personal website & blog
Vue
11
star
49

vue-proxi

💠 Tiny proxy component for Vue.js
JavaScript
11
star
50

bfs

Find the path of a value in a complex JavaScript object graph/tree.
JavaScript
11
star
51

prerelease-checks

Run essential pre-release checks before releasing an npm package
TypeScript
11
star
52

git-detect-case-change

🤖 Script to detect file name case changes in a Git repository
TypeScript
10
star
53

cli-simple-table

Simple CLI table for simple people
TypeScript
9
star
54

webpack-test-utils

Utility functions to test Webpack loaders/plugins
TypeScript
8
star
55

vue-svg-icon-set

Efficiently expose a SVG icon set in Vue
JavaScript
8
star
56

webpack-playground

Demonstration of different Webpack configurations
JavaScript
8
star
57

eslint-config

TypeScript
7
star
58

vue-v

Tiny component to render Vue.js vNodes in the template.
JavaScript
7
star
59

i-peers

npx package to install local peer-dependencies
JavaScript
7
star
60

fs.promises.exists

🪐 The missing fs.promises.exists(). Also supports case-sensitive/insensitive file paths.
TypeScript
7
star
61

vue-just-ssr

🔥 Instantly add a Vue SSR dev-env to your Webpack build
JavaScript
7
star
62

issue-reproductions

A repository to collect and organize my issue reproductions
JavaScript
6
star
63

webpack-analyze-duplication-plugin

Detect duplicated modules in your Webpack build
JavaScript
6
star
64

vue-feather-icon-set

Optimized Feather icon set for Vue using SVG references
JavaScript
6
star
65

is-fs-case-sensitive

Check whether the file-system is case-sensitive
TypeScript
6
star
66

npm-registry-sync

A daemon to sync packages across npm registries
TypeScript
6
star
67

babel-plugin-debug-object-location

Babel plugin to help you determine where an object or array was instantiated
TypeScript
5
star
68

generate-batched-pr-manifest

Generate a manifest of all the PRs included in a batched PR
TypeScript
5
star
69

entry-file-plugin

Create an ESM entry-file in your Webpack build to consolidate entry-point exports
TypeScript
5
star
70

privatenumber

5
star
71

webpack-dependency-size

👩‍🔬 Webpack plugin to get an overview of bundled dependencies and their size
JavaScript
5
star
72

vue-demo-collapse

Vue component that shows a demo and a "Show Code" button to expand source code
Vue
4
star
73

markdown-it-add-attrs

markdown-it plugin to add attributes to all rendered elements
JavaScript
4
star
74

browser-reload-plugin

Automatically reload the browser page on every Webpack watch build
JavaScript
4
star
75

rollup-playground

Demonstration of different Rollup configurations
JavaScript
3
star
76

rollup-plugin-htmlvue

Rollup plugin for transforming HTML/XML to Vue SFC
TypeScript
3
star
77

htmlvue-loader

Webpack loader for compiling HTML to Vue
JavaScript
3
star
78

vue-ast-utils

Utils for working with Vue 3 AST nodes
TypeScript
3
star
79

systemjs-unpkg

SystemJS extra to auto-resolve bare specifiers to UNPKG
JavaScript
3
star
80

postcss-custom-properties-transformer

PostCSS plugin to apply transformations to CSS custom properties (eg. mangling)
JavaScript
2
star
81

web-diff

Visually diff web pages
JavaScript
2
star
82

rollup-plugin-aggregate-exports

Emit an entry file to aggregate exports across multiple files.
JavaScript
2
star
83

svg-trace-loader

Webpack loader to trace and flatten SVGs into one path
JavaScript
2
star
84

repkg

🚚 On-demand AMD npm package bundling service
JavaScript
2
star
85

webpack-distsize

Track Webpack output size via version control
JavaScript
2
star
86

motion-orientation-api

Motion & Orientation API explorer
Vue
2
star
87

vue-server-renderer

JavaScript
2
star
88

postcss-import-alias

Use aliases in your PostCSS import statements
JavaScript
2
star
89

pm2-no-daemon-bug

JavaScript
1
star
90

resume

1
star
91

fs-router-patch

Add routing for shimming fs access
JavaScript
1
star
92

gulp-watchman

JavaScript
1
star
93

.github

1
star
94

sharp-vs-resvgjs

JavaScript
1
star
95

mempack

Run a Webpack build in-memory
JavaScript
1
star