简易版购物车案例(vue)
<div id="app">
<div v-if="books.length">
<table>
<thead>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</thead>
<tbody>
<tr v-for="(item,index) in books">
<!-- 1.item是对象 遍历对象 -->
<!-- <td v-for="value in item">{{value}}</td> -->
<!-- 2. -->
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.data}}</td>
<td> {{item.price | showPrice}}
</td>
<td><button @click="sub(index)" v-bind:disabled="item.number <= 1">-</button>{{item.number}}
<!-- disabled禁用 -->
<button @click="add(index)">+</button>
</td>
<td @click="remove"><a href="#">删除</a></td>
</tr>
</tbody>
</table>
<h2>总价{{totalnumber|showPrice}}</h2>
</div>
<div v-else>购物车为空</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
const app = new Vue({
el: "#app",
data: {
books: [{
id: 1,
name: "书籍1",
data: "2006-9",
price: 88,
number: 1
}, {
id: 2,
name: "书籍1",
data: "2006-9",
price: 88,
number: 1
}, {
id: 3,
name: "书籍1",
data: "2006-9",
price: 88,
number: 1
}, {
id: 4,
name: "书籍1",
data: "2006-9",
price: 88,
number: 1
}, {
id: 5,
name: "书籍1",
data: "2006-9",
price: 88,
number: 1
}]
},
methods: {
sub(index) {
// console.log(index);
// if (
// this.books[index].number > 1
// )
this.books[index].number--
},
add(index) {
this.books[index].number++
},
remove(index) {
this.books.splice(index, 1)
}
},
// 过滤器
filters: {
showPrice(price) {
return "¥" + price.toFixed(2)
}
},
computed: {
totalnumber() {
// 1.普通方法
// let total = 0
// for (let i = 0; i < this.books.length; i++) {
// total += this.books[i].price * this.books[i].number
// }
// return total
// 2.
// let total = 0
// for (let i of this.books) {
// total += this.books[i].price * this.books[i].number
// }
// return total
// 3.
let total = 0
for (let item of this.books) {
total += item.price * item.number
}
return total
}
}
})
</script>
<style>
table {
border: 1px solid #000;
border-collapse: collapse;
border-spacing: 0;
}
th,
td {
padding: 8px 16px;
border: 1px solid #000;
text-align: left;
}
th {
background-color: #f7f7f7;
color: #5c6b77;
font-weight: 600;
}
</style>