Vue完成购物车
程序员文章站
2022-03-24 09:36:30
...
<template>
<div>
<div class="cart">
<h2>购物车</h2>
<table>
<thead>
<tr>
<th></th>
<th>编号</th>
<th>商品名称</th>
<th>价格</th>
<th>购买数量</th>
<th>金额</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in books">
<td>
<input type="checkbox" v-model="selectBook" :value="index" />
</td>
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>
¥<span>{{ item.price }}</span>
</td>
<td>
<button @click="sub(index, $event)" :disabled="item.count <= 1">
-
</button>
<span>{{ item.count }}</span>
<button @click="add(index, $event)" :disabled="item.count >= 10">
+
</button>
</td>
<td class="amount">{{ item.price * item.count }}</td>
<td><button @click="del(index)">删除</button></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5">总金额:</td>
<td colspan="2">
<span class="total">{{ gettotal }}</span>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
</template>
<script>
export default {
name: "App2",
data() {
return {
books: [
{ id: 1, name: "细说 PHP", price: 158, active: false, count: 1 },
{ id: 2, name: "细说网页制作", price: 158, active: false, count: 2 },
{ id: 3, name: "细说 JavaScript", price: 158, active: false, count: 1 },
{
id: 4,
name: "细说 HTML5 高级 API",
price: 158,
active: false,
count: 1,
},
{ id: 5, name: "细说 DOM 和 BOM", price: 158, active: false, count: 1 },
],
selectBook: [],
};
},
methods: {
sub(index, event) {
if (this.books[index].count > 1) {
this.books[index].count--;
}
},
add(index, event) {
if (this.books[index].count < 10) {
this.books[index].count++;
}
},
del(index) {
this.books.splice(index, 1);
},
},
computed: {
gettotal: {
get() {
let total = 0;
this.selectBook.forEach(
(id) => (total += this.books[id].price * this.books[id].count)
);
return total;
},
},
},
};
</script>
<style lang="less">
.cart {
width: 700px;
margin: 0 auto;
}
h2 {
text-align: center;
}
.cart table {
width: 700px;
border-collapse: collapse;
}
td,
th {
border: 1px solid;
}
</style>
上一篇: html怎么设置div边距
下一篇: PHP数组重新排序