JSFiddle - React, Tailwind, and code Playground
by flourscent
HTML
<!DOCTYPE html>
<title>Vue.Stationery store</title>
<script src="https://unpkg.com/[email protected]"></script>
<div id="app">
<ul>
<li v-for="item in items" v-bind:key="item.name">
{{ item.name }}의 개수 : <input type="number" v-model="item.quantity" min="0">
</li>
</ul>
<hr>
<div v-bind:style="errorMessageStyle">
<ul>
<li v-for="item in items" v-bind:key="item.name">
{{ item.name }}: {{ item.price }} x {{ item.quantity }} = {{ item.price *
item.quantity | numberWithDelimiter }} 원
</li>
</ul>
<p>{{ items[0].name }}: {{ items[0].price }} x {{ items[0].quantity }}</p>
<p> 소계 : {{ totalPrice | numberWithDelimiter }} 원 </p>
<p> 합계(세포함): {{ totalPriceWithTax | numberWithDelimiter }} 원 </p>
<p v-show="!canBuy">
{{ 1000 | numberWithDelimiter }} 이상부터 구매 가능
</p>
<!-- ボタンが押されたら、メソッドを呼び出す -->
<button v-bind:disabled="!canBuy" v-on:click="doBuy"> 구매 </button>
</div>
</div>
JavaScript
var items = [
{
name: '연필',
price: 300,
quantity: 0
},
{
name: '공책',
price: 400,
quantity: 0
},
{
name: '지우개',
price: 500,
quantity: 0
}
]
var vm = new Vue({
el: '#app',
data: {
items: items
},
filters: {
numberWithDelimiter: function (value) {
if (!value) {
return '0'
}
return value.toString().replace(/(\d)(?=(\d{3})+$)/g, '$1,')
}
},
methods: {
doBuy: function () {
// 本来はここで、サーバーと通信を行う
alert(this.totalPriceWithTax + '원 구매하였습니다!')
this.items.forEach(function (item) {
item.quantity = 0
})
}
},
computed: {
totalPrice: function () {
return this.items.reduce(function (sum, item) {
return sum + (item.price * item.quantity)
}, 0)
},
totalPriceWithTax: function () {
return Math.floor(this.totalPrice * 1.10)
},
canBuy: function () {
return this.totalPrice >= 1000
},
errorMessageStyle: function () {
// canBuy が偽の時に赤く表示する
return {
border: this.canBuy ? '' : '1px solid red',
color: this.canBuy ? '' : 'red'
}
}
}
})
window.vm = vm