Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A way to render multiple root elements on VueJS with v-for directive

Right now, I'm trying to make a website that shows recent news posts which is supplied my NodeJS API.

I've tried the following:

HTML

<div id="news" class="media" v-for="item in posts">
    <div>
        <h4 class="media-heading">{{item.title}}</h4>
        <p>{{item.msg}}</p>
    </div>
</div>

JavaScript

const news = new Vue({
    el: '#news',
    data:   {
        posts:  [
            {title: 'My First News post',   msg: 'This is your fist news!'},
            {title: 'Cakes are great food', msg: 'Yummy Yummy Yummy'},
            {title: 'How to learnVueJS',    msg: 'Start Learning!'},
        ]
    }
})

Apparently, the above didn't work because Vue can't render multiple root elements.

I've looked up the VueJS's official manual and couldn't come up with a solution. After googling a while, I've understood that it was impossible to render multiple root element, however, I yet to have been able to come up with a solution.

like image 836
HelloWorld Avatar asked Nov 27 '17 13:11

HelloWorld


1 Answers

The simplest way I've found of adding multiple root elements is to add a single <div> wrapper element and make it disappear with some CSS magic for the purposes of rendering.

For this we can use the "display: contents" CSS property. The effect is that it makes the container disappear, making the child elements children of the element the next level up in the DOM.

Therefore, in your Vue component template you can have something like this:

<template>
    <div style="display: contents"> <!-- my wrapper div is rendered invisible -->
        <tr>...</tr>
        <tr>...</tr>
        <tr>...</tr>
    </div>
</template>

I can now use my component without the browser messing up formatting because the wrapping <div> root element will be ignored by the browser for display purposes:

<table>
   <my-component></my-component> <!-- the wrapping div will be ignored -->
</table>

Note however, that although this should work in most browsers, you may want to check here to make sure it can handle your target browser.

like image 114
Cosmin Dumitrache Avatar answered Oct 29 '22 00:10

Cosmin Dumitrache