vue组件不呈现它从后端获得的数据



我有一个非常基本的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}}也是如此

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>

数据应该返回一个返回新对象的函数:

短期

data: () => ({
products: []
})

远程

data() {
return {
products: []
}
}

最新更新