Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

components - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...