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

前端 未结 5 1695
轮回少年
轮回少年 2020-12-11 07:21

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

5条回答
  •  庸人自扰
    2020-12-11 07:55

    The simplest way I've found of adding multiple root elements is to add a single

    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:

    
    

    I can now use my component without the browser messing up formatting because the wrapping

    root element will be ignored by the browser for display purposes:

    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.

提交回复
热议问题