我有一个非常基本的HTML页面,其中包含一个简单的Vue组件。在“网络”标签中,我可以看到它正确地获取了数据,呈现了应该出现的列表,但是数据根本不在那儿。
<div id="app">
<h2>Total inventory: {{ totalProducts }}</h2>
<ul>
<li>beginning of the list</li>
<li v-for="product in products">
{{ product.name }} {{ product.price }}
</li>
<li>End of the list</li>
</ul>
</div>
<script src="https://unpkg.com/vue"></script>
<script>
const app = new Vue({
el: '#app',
data: {
products: []
},
created () {
fetch('http://localhost:3000/api/teddies')
.then(response => response.json())
.then(json => {
this.products = json.products
})
},
computed () {
return this.products.reduce((sum, product) => {
return sum + product.quantity
}, 0)
}
})
</script>
我尝试使用axios将该请求的脚本代码包含到一个单独的文件中(我知道它不会更改任何事情,因为该请求实际上已经生效),将一个ID直接分配给列表并在脚本中使用它...没有什么可以代替{{product.name}}和{{product.price}}。 totalProducts变量和{{totalProducts}}
答案 0 :(得分:2)
像这样直接将json
分配给this.products
:
fetch('https://fakestoreapi.com/products')
.then(response => response.json())
.then(json => {
this.products = json
})
因为json
代表products
列表,所以json.products
将返回undefined
,计算出的属性应定义如下:
computed:{
comp1(){...},
comp2(){...}
}
<div id="app">
<h2>Total inventory: {{ totalProducts }}</h2>
<ul>
<li>beginning of the list</li>
<li v-for="product in products">
{{ product.title }} {{ product.price }}
</li>
<li>End of the list</li>
</ul>
</div>
<script src="https://unpkg.com/vue"></script>
<script>
const app = new Vue({
el: '#app',
data: {
products: []
},
created() {
fetch('https://fakestoreapi.com/products')
.then(response => response.json())
.then(prod => {
this.products = prod
})
},
computed: {
totalProducts() {
return this.products.reduce((sum, product) => {
return sum + product.price
}, 0)
}
}
})
</script>
答案 1 :(得分:0)
您的数据应返回一个返回新对象的函数:
捷径
data: () => ({
products: []
})
很远
data() {
return {
products: []
}
}