JSFiddle - React, Tailwind, and code Playground
by Avizura
HTML
<div id="app">
<div class="container">
<market :market-items="marketItems" v-on:add-item="addItem"></market>
<customer :basket-items="basketItems" v-on:remove-item="removeItem"></customer>
</div>
<div class="cash">
Available money: {{cash}} $
</div>
<div class="total">
Total: {{total}} $
</div>
</div>
CSS
.container {
display: flex;
}
.product-list {
flex: 1 1 auto;
}
.product-item {
padding: 10px;
}
.product-item:hover {
background: yellow;
}
.title {
background: pink;
padding: 10px;
}
.title:last-child {
background: purple;
}
.market {
background: green;
}
.basket {
background: blue;
}
.total {
background: red;
}
JavaScript
class Market {
getProducts() {
return [
{
'id': 1,
'title': 'MacBook',
'price': 100
},
{
'id': 2,
'title': 'GTR',
'price': 99
},
{
'id': 3,
'title': 'apple',
'price': 20
},
{
'id': 4,
'title': 'iphone',
'price': 144
},
{
'id': 5,
'title': 'nexus',
'price': 233
},
]
}
}
const market = new Market();
const marketItems = market.getProducts();
Vue.component('market', {
template: '<div class="market product-list"><div class="title">Список товаров</div><div v-for="item in marketItems" class="product-item" v-on:click="handleItemClick(item)">{{item.title}} ({{item.price}}$)</div></div>',
props: ['marketItems'],
methods: {
handleItemClick: function(item) {
this.$emit('add-item', item);
}
}
});
Vue.component('customer', {
template: '<div class="basket product-list"><div class="title">Корзина</div><div v-for="item in basketItems" class="product-item" v-on:click="handleItemClick(item)">{{item.title}}</div></div>',
props: ['basketItems'],
methods: {
handleItemClick: function(item) {
this.$emit('remove-item', item);
}
}
})
var app = new Vue({
el: '#app',
data: {
marketItems,
basketItems: [],
total: 0,
cash: 500
},
methods: {
addItem: function(item) {
console.log(item);
let newTotal = this.total + item.price;
if (this.cash < newTotal ) {
alert('You don\'t have enough money to buy it!');
return;
}
this.basketItems.push(item);
debugger;
this.marketItems = this.marketItems.filter(i => i.id !== item.id);
this.total = newTotal;
},
removeItem: function(selectedItem) {
this.marketItems.push(selectedItem);
this.basketItems = this.basketItems.filter(item => item.id !== selectedItem.id);
this.total -= selectedItem.price;
}
}
});