Reputation: 141
I have a very basic HTML page with a simple Vue component. In the network tab I can see it gets the data correctly, the list where it should appear is rendered, but the data is simply not there.
<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>
I tried including the script's code into a separate file, using axios for the request (I knew it wouldn't change a thing because the request actually works already), attributing an ID directly to the list and using that in the script... nothing appeared in place of {{ product.name }} and {{ product.price }} . Same goes for the totalProducts variable and {{ totalProducts }}
Upvotes: 1
Views: 484
Reputation: 1
Assign json
directly to this.products
like :
fetch('https://fakestoreapi.com/products')
.then(response => response.json())
.then(json => {
this.products = json
})
because json
represents the products
list, so json.products
will return undefined
and the computed property should be defined as follows :
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>
Upvotes: 2
Reputation: 4240
You data should return a function that returns a new object:
Short way
data: () => ({
products: []
})
Long way
data() {
return {
products: []
}
}
Upvotes: 1