<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>购物车-v-model</title>
<style>
table {
border-collapse: collapse;
}
thead {
background-color: aliceblue;
}
th,
td {
border: 1px solid #aaa;
padding: 8px 16px;
}
</style>
</head>
<body>
<div id="app">
<template v-if="books.length">
<table>
<thead>
<tr>
<th>序号</th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in books" :key="item.id">
<td>{{index + 1}}</td>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<td>¥{{item.price}}</td>
<td>
<button @click="decrement(index,item)">-</button>
{{item.count}}
<button @click="increment(index,item)">+</button>
</td>
<td>
<button @click="removeBook(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<h2>¥{{totalPrice}}</h2>
</template>
<h1 v-else>购物车为空,请添加买的书籍~</h1>
</div>
<script src="vue.js"></script>
<script src="./data/data.js"></script>
<script>
console.log(books)
const app = Vue.createApp({
data: function () {
return {
books: books
}
},
computed: {
totalPrice() {
let price = 0
for (const item of this.books) {
price += item.price * item.count
}
return price
}
},
methods: {
decrement(index, item) {
console.log("点击-")
this.books[index].count--
},
increment(index,item) {
console.log(index, item)
console.log("点击+:", index)
//this.books[index].count++
item.count++
},
removeBook(index){
this.books.splice(index,1)
}
}
})
const vm = app.mount('#app')
</script>
</body>
</html>