我正在加载来自.json的数据,但V-For不会返回循环。
我的html:
<div id="app">
<template v-for="product in products">
<p>{{ product.brand }}</p>
<p>{{ product.images }}</p>
<p>{{ product.id }}</p>
<p>{{ product.title }}</p>
<p>{{ product.description }}</p>
<p>{{ product.price }}</p>
</template>
</div>
我的JS:
new Vue({
el: '#app',
data: {
products: []
},
methods: {
},
created: function() {
var self = this;
self.$http.get('http://localhost/app/products.json').then(function(response) {
self.products = response.body;
});
}
});
我的JSON:
"product": [
{
"brand": "Apple",
"images":"images/iphone-x-64-gb.jpg",
"id": "iphone-x-64-gb",
"title": "iPhone X 64 GB",
"description": "Lorem ipsum dolor",
"price": "1.159,00"
},
{
"brand": "Apple",
"images":"images/iphone-x-256-gb.jpg",
"id": "iphone-x-256-gb",
"title": "iPhone X 256 GB",
"description": "Lorem ipsum dolor",
"price": "1.329,00"
},
{
"brand": "Apple",
"images":"images/iphone-8-64-gb.jpg",
"id": "iphone-8-64-gb",
"title": "iPhone 8 64 GB",
"description": "Lorem ipsum dolor.",
"price": "819,99"
}
]
}
如果我在html中写了这样的作品,但是如果我放例如
将模板更改为如下...
<template>
<div class="wrapper">
<div v-for="product in products">
<p>{{ product.brand }}</p>
<p>{{ product.images }}</p>
<p>{{ product.id }}</p>
<p>{{ product.title }}</p>
<p>{{ product.description }}</p>
<p>{{ product.price }}</p>
</div>
</div>
</template>
vue模板在 <template>
标签之间需要一个根元素,而且我相信v-for在根元素上无法正常工作,因此我将其嵌套在"包装器"中。
如果您查看开发工具控制台,则可能会看到一个说明类似的错误。
Cannot use v-for on stateful component root element because it
renders multiple elements.
或
[Vue warn]: Multiple root nodes returned from render function.
Render function should return a single root node.
附加
此外,您的代码似乎还有其他问题。在我看来,您的要求应该像以下内容一样,除非我缺少有关您的JSON返回方式的内容。
created: function() {
this.$http.get('http://localhost/app/products.json').then(function(response) {
this.products = response.body.products;
}.bind(this));
},
请注意,从response.body
到response.body.products
的更改也可以将self
分配给this
,但我发现使用.bind(this)
更简洁。
这是基于您的代码的工作小提琴。https://jsfiddle.net/skribe/umx98rxm/