the code: shop.vue
<template>
<div >
<div v-for="Product in items" :key="Product.id" :Product="Product"
v-on:add-To-Cart="addToCart($event)">
<h1>{{ Product.name }}</h1> <img :src="Product.pic" width="400" /> <br>
{{ Product.description }} <br>
{{ "$" Product.price }} <br>
<button @click="$emit('add-To-Cart', 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.Product=Product
console.log(this.Product)
}
}
}
</script>
when I click the add to cart button it is not logging the product to the console
how can I fix that? and implement a shopping cart to my website?
CodePudding user response:
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 >
<div 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 @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>
CodePudding user response:
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://www.taste.com.au/recipes/chocolate-cream-biscuits/ee3d0934-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://www.taste.com.au/recipes/chocolate-cream-biscuits/ee3d0934-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 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 @click="addToCart(product)">Add to Cart</button>
</div>
</div>