Last active
July 8, 2019 13:25
-
-
Save eladcandroid/bf32d759d2e2f4456c82c2a14d7e7828 to your computer and use it in GitHub Desktop.
Vue.js live exercise - Products with cart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8" /> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |
<title>My App</title> | |
<meta name="viewport" content="width=device-width, initial-scale=1" /> | |
<script src="lib/vue.js"></script> | |
<!-- <script src="https://cdn.jsdelivr.net/npm/vue-router/dist/vue-router.js"></script> --> | |
</head> | |
<body> | |
<style> | |
.product { | |
border: 1px solid black; | |
float: left; | |
height: 200px; | |
width: 300px; | |
margin: 10px; | |
padding: 20px; | |
} | |
.add-to-cart { | |
background-color: rgba(171, 171, 247, 0.794); | |
color: #000; | |
font-size: 20px; | |
border-radius: 10px; | |
width: 100%; | |
} | |
</style> | |
<div id="app"> | |
<cart :count="cartCount" :cart-products="cartProducts"></cart> | |
<product class="product" v-for="product in products" | |
:description="product.description" | |
:key="product.id" | |
:id="product.id" | |
:image="product.image" @add-to-cart="addToCart"></product> | |
</div> | |
<script> | |
Vue.component('cart', { | |
props: ['count', 'cartProducts'], | |
template: `<div> | |
<img src="images/cart.png" width="40"/> | |
<span>{{count}}</span> | |
<ul> | |
<li v-for="cartProduct in cartProducts">{{cartProduct.description}}</li> | |
</ul> | |
</div>` | |
}) | |
Vue.component('product', { | |
props: ['description', 'image', 'id'], | |
template: `<div> | |
<button class="add-to-cart" @click="$emit('add-to-cart', id)">Add to cart</button> | |
<div class="description">Item Description: {{description}}</div> | |
<div class="image"><img :src="image" width="100"/></div> | |
</div>` | |
}) | |
new Vue({ | |
el: '#app', | |
methods: { | |
addToCart(id) { | |
this.cartCount++; | |
const product = this.products.find(product=> product.id === id) | |
this.cartProducts.push(product) | |
} | |
}, | |
data: { | |
products: [ | |
{ | |
id: 1, | |
description: 'Black Shoes', | |
image: 'images/black-shoes.jpg' | |
}, | |
{ | |
id: 2, | |
description: 'Funny T-Shirt', | |
image: 'images/tshirt.jpg' | |
} | |
], | |
cartProducts: [ | |
], | |
cartCount: 0 | |
} | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment