一种使用 v-for 指令在 VueJS 上渲染多个根元素的方法 [英] A way to render multiple root elements on VueJS with v-for directive
问题描述
现在,我正在尝试制作一个显示最近新闻帖子的网站,该网站由我的 NodeJS API 提供.
我尝试了以下方法:
HTML
<div><h4 class="media-heading">{{item.title}}</h4><p>{{item.msg}}</p>
JavaScript
const news = new Vue({el: '#news',数据: {帖子: [{title: 'My First News post', msg: '这是你的第一条新闻!'},{title: '蛋糕是美味的食物', msg: 'Yummy Yummy Yummy'},{title: '如何学习VueJS', msg: '开始学习!'},]}})
显然,上面的方法不起作用,因为 Vue 无法渲染多个根元素.
我查了 VueJS 的官方手册,没有找到解决办法.谷歌搜索一段时间后,我明白不可能渲染多个根元素,但是,我还没有想出一个解决方案.
您可以使用渲染函数拥有多个根元素(或组件)>
一个简单的例子是有一个渲染多个 元素的组件:
<li>项目</li><li>项目2</li>... 等等模板>
但是上面会抛出一个错误.要解决此错误,可以将上述模板转换为:
出口默认{功能:真实,渲染(创建元素){返回 [createElement('li', 'Item'),createElement('li', 'Item2'),]}}
但是,正如您可能已经注意到的那样,例如,如果您想显示 50 里的项目,这会变得非常乏味.因此,最终,要动态显示元素,您可以执行以下操作:
出口默认{功能:真实,props: ['listItems'],//这是一个`<li>`名称数组(例如['Item', 'Item2'])渲染(创建元素,{道具}){返回 props.listItems.map(name => {返回 createElement('li', name)})}}
INFO 在这些示例中,我使用了属性 functional: true 但当然不需要使用渲染函数".请考虑在此处
了解有关功能组件的更多信息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.
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
这篇关于一种使用 v-for 指令在 VueJS 上渲染多个根元素的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!