我正在使用v-for
循环编写一些Vue.js代码。其中只有一个HTML节点,但是Vue抛出两个错误:
vue.js:597 [Vue warn]: Error compiling template:
<div id="products" v-for="p in productList">
<div class="col-sm-4 col-md-3">
<figure class="figure">
<img src="img/worship_area.JPG" class="figure-img img-fluid rounded" alt="Worship Area">
<figcaption class="">{{ p.name }}</figcaption>
</figure>
</div>
</div>
- Cannot use v-for on stateful component root element because it renders multiple elements.
(found in <Root>)
和
[Vue warn]: Multiple root nodes returned from render function. Render function should return a single root node.
(found in <Root>)
我的JavaScript是:
var products;
$(document).ready(() => {
products = new Vue({
el: "#products",
data: {
productList: [
{name:"Worship Area"}
]
}
});
});
,所引用的HTML是:
<div id="products" v-for="p in productList">
<div class="col-sm-4 col-md-3">
<figure class="figure">
<img src="img/worship_area.JPG" class="figure-img img-fluid rounded" alt="Worship Area" />
<figcaption class="">{{ p.name }}</figcaption>
</figure>
</div>
</div>
知道我在做什么错吗?我只在#products中看到一个标签,但它在抱怨多个元素。页面中只有一个元素,其id属性为products
,这是上面引用的元素。
答案 0 :(得分:2)
您应该将html元素包装成单个根元素:
<div id="products"><!-- now, it is the root element -->
<div v-for="p in productList">
<div class="col-sm-4 col-md-3">
<figure class="figure">
<img src="img/worship_area.JPG" class="figure-img img-fluid rounded" alt="Worship Area" />
<figcaption class="">{{ p.name }}</figcaption>
</figure>
</div>
</div>
</div>
答案 1 :(得分:0)
即使乍一看它看起来像是单个根,v-for
伪指令仍会根据循环变量呈现其多个副本。因此,主根元素必须是不可循环的。
您可以将模板代码与另一个div包装在一起,然后将代码更改为以下形式:
<div id="products">
<div v-for="p in productList">
<div class="col-sm-4 col-md-3">
<figure class="figure">
<img src="img/worship_area.JPG" class="figure-img img-fluid rounded" alt="Worship Area">
<figcaption class="">{{ p.name }}</figcaption>
</figure>
</div>
</div>
</div>