0👍
Custom events are emitted from vue components not from native html elements, the same for props, you can directly call the method addToCart
from the click event handler :
<template>
<div class="shop">
<div class="products" v-for="Product in items" :key="Product.id" >
<h1>{{ Product.name }}</h1> <img :src="Product.pic" width="400" /> <br>
{{ Product.description }} <br>
{{ "$" + Product.price }} <br>
<button class="addToCart" @click="addToCart(Product)">Add to Cart</button>
</div>
</div>
</template>
<script>
import Product from '../db.json';
export default {
name: 'shop',
data() {
return {
items: Product
}
},
methods: {
addToCart(Product) {
this.items.push(Product)
console.log(this.items)
}
}
}
</script>
0👍
I have a modified the code a little bit without any stylings applied. Please check the below snippet
new Vue({
el: '#app',
data() {
return {
items: [{
name: 'aaa',
description: 'about aaa',
pic: 'https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.taste.com.au%2Frecipes%2Fchocolate-cream-biscuits%2Fee3d0934-ccca-4fdf-8827-64f2fd2737e1&psig=AOvVaw1fEqbEmoJeGS0WmrnSy6pS&ust=1668580370820000&source=images&cd=vfe&ved=0CBAQjRxqFwoTCICb2LbIr_sCFQAAAAAdAAAAABAD',
price: 12,
},
{
name: 'bbb',
description: 'about bbb',
pic: 'https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.taste.com.au%2Frecipes%2Fchocolate-cream-biscuits%2Fee3d0934-ccca-4fdf-8827-64f2fd2737e1&psig=AOvVaw1fEqbEmoJeGS0WmrnSy6pS&ust=1668580370820000&source=images&cd=vfe&ved=0CBAQjRxqFwoTCICb2LbIr_sCFQAAAAAdAAAAABAD',
price: 12,
}],
cartItems:[],
};
},
methods: {
addToCart(item) {
this.cartItems.push({...item});
},
}
});
.products {
display: flex;
justify-content: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div class="products" v-for="product in items" :key="product.id">
<h1>{{ product.name }}</h1> <img :src="product.pic" width="400" /> <br>
{{ product.description }} <br>
{{ "$" + product.price }} <br>
<button class="addToCart" @click="addToCart(product)">Add to Cart</button>
</div>
</div>
Source:stackexchange.com