Reputation: 96
I have sent an array of objects of data into a child component through props, then ran a v-for and it printed the elements in the manner I want, like this
<div class="col-md-3" v-for="product in products" :key="product.id" v-if="product.id <= 8" >
<div>{{ product.name }}</div>
<button @click="buyProduct">
</div>
and ran this method:
buyProduct(){
console.log('bought');
const order = {
orderId: this.product.id,
orderName: this.product.productName,
orderImg: this.produc.image,
orderOriginalPrice: this.product.originalPrice,
orderdiscountPrice: this.products.discountPrice,
orderQuantity: this.quantity,
};
console.log(this.products);
}
but my console gives me "TypeError: Cannot read property 'id' of undefined"
any ideas or suggestions please? as I would like to get the values of those products I click on
Upvotes: 0
Views: 249
Reputation: 7140
I assume this is the row that throws your error: orderId: this.product.id,
You probably never set this.product
, a better way would be to call your buyProduct
method with the clicked product as parameter:
<button @click="buyProduct(product)">buy me</button>
and
buyProduct(product) {
...
orderId: product.id
...
}
Also don't combine v-for
and v-if
in the template (you probably already get a warning about this), instead use a computed
property if you really want to filter the passed products
further:
computed: {
filteredProducts() {
return this.products.filter(p => p.id <= 8)
}
}
and then v-for="product in filteredProducts"
Upvotes: 1