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

徘徊边缘 提交于 2019-12-02 06:17:40

Vue requires that there be a single root node. However, try changing your html to this:

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

This change allows for a single root node id="news" and yet still allows for rendering the lists of recent posts.

You can have multiple root elements (or components) using render functions

A simple example is having a component which renders multiple <li> elements:

<template>
 <li>Item</li>
 <li>Item2</li>
 ... etc
</template>

However the above will throw an error. To solve this error the above template can be converted to:

export default {
 functional: true,
 render(createElement) {
  return [
    createElement('li', 'Item'),
    createElement('li', 'Item2)
  ]
 }
}

But again as you probably noticed this can get very tedious if for example you want to display 50 li items. So, eventually, to dynamically display elements you can do:

export default {
 functional: true,
 props: ['listItems'], //this is an array of `<li>` names (e.g. ['Item', 'Item2'])

 render(createElement, { props }) {
   return props.listItems.map(name => {
     return createElement('li', name)
   })
 }
}

INFO in those examples i have used the property functional: true but it is not required of course to use "render functions". Please consider learning more about functional componentshere

Multiple root elements are not supported by Vue (which caused by your v-for directive, beacause it may render more than 1 elements). And is also very simple to solve, just wrap your HTML into another Element will do.

For example:

<div id="app">
   <!-- your HTML code -->
</div>

and the js:

var app = new Vue({
  el: '#app', // it must be a single root!
  // ...
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!