一种使用v-for指令在VueJS上呈现多个根元素的方法 [英] A way to render multiple root elements on VueJS with v-for directive

查看:208
本文介绍了一种使用v-for指令在VueJS上呈现多个根元素的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我正在尝试创建一个网站,以显示NodeJS API提供的最新新闻。

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

我尝试了以下操作:


HTML

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

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!'},
        ]
    }
})

显然,以上操作不起作用,因为Vue无法呈现多个根元素。

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

我查看了VueJS的官方手册,但没有提出解决方案。
经过一段时间的搜索后,我了解到无法渲染多个根元素,但是,我仍然无法提出解决方案。

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.

推荐答案


您可以使用渲染函数

一个简单的示例就是一个具有多个< li> 元素:

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'),
  ]
 }
}

但是您可能还注意到,例如,这可能会变得非常乏味您要显示50 li项目。因此,最终,要动态显示元素,您可以执行以下操作:

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 在这些示例中,我使用了属性 functional:true ,但当然不需要使用渲染功能。请考虑在此处

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

这篇关于一种使用v-for指令在VueJS上呈现多个根元素的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆