初识vue实现购物车小小的案例
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
html:
<div id="app">
商品名称:<input type="text" v-model="item.name">
商品价格:<input type="number" v-model="item.price">
<button @click="add">增加</button> // 添加商品
<table class="table table-bordered" style="width: 600px;margin:20px auto;">
<tr>
<th>商品名字</th>
<th>价格</th>
<th>购买数量</th>
<th>小计</th>
<th>操作</th>
</tr>
<tr v-if="items.length === 0">
<td colspan="5" class="text-center">
暂无商品
</td>
</tr>
<tr v-for="(item,index) in items">
<td>
<input type="checkbox" @change="itemSelectedChange" v-model="item.selected">
{{item.name}}
</td>
<td>
¥ {{item.price}}
</td>
<td>
<button @click="addNum(index)" class="btn btn-xs">+</button>
<span>{{item.num}}</span>
<button class="btn btn-xs" @click="reduceNum(index)">-</button>
</td>
<td>
¥{{ (item.num*item.price).toFixed(2) }}
</td>
<td>
<button class="btn btn-danger" @click="delItem(index)">删除</button>
</td>
</tr>
<tr>
<td>合计:</td>
<td colspan="4">
全选:
<input type="checkbox" @change="allCheckedChange" v-model="allChecked">
总价格:¥{{total}}
</td>
</tr>
</table>
</div>
script:
<script>
const vm = new Vue({
el: '#app',
data: {
// 商品:{商品名 商品价格 默认商品购买个数1 默认选中} 用于添加商品
item: {
name: '',
price: 0,
num: 1,
selected: true
},
items: [{
name: '商品1',
price: 18.8,
num: 1,
selected: true
},
{
name: '商品2',
price: 28.8,
num: 2,
selected: true
},
{
name: '商品3',
price: 166.88,
num: 1,
selected: true
},
{
name: '商品4',
price: 188,
num: 1,
selected: true
}
],
allChecked: true, // 全选多选框
total: 0 // 合计
},
methods: {
add() {
// 注意点:将item进行浅克隆,如果直接添加时是引用传递,对数据会有影响。
this.items.push({...this.item})
// 重新计算合计
this.calcTotal();
// 清空添加输入框
this.item.name=''
this.item.price=0
},
// 全选
allCheckedChange() {
// 将每一个商品的多选框的值赋值为全选的多选框的值,即全选选中 所有商品就被选中 全选不选中 所有商品不选中
this.items.forEach(item => {
item.selected = this.allChecked
})
// 全选后再次进行合计
this.calcTotal();
},
// 商品勾选改变状态 改变合计 和 全选状态
itemSelectedChange() {
this.calcAllChecked();
this.calcTotal();
},
// 删除商品 删除商品 和 改变合计
delItem(index) {
if (confirm('确认删除吗?')) {
this.items.splice(index, 1);
this.calcTotal();
}
},
// 减少商品数量 减少为0 时就删除这个商品
reduceNum(index) {
this.items[index].num--;
if (this.items[index].num === 0) {
if (confirm('确认删除吗?')) {
this.items.splice(index, 1);
} else {
this.items[index].num = 1;
}
}
this.calcTotal();
},
// 添加商品数量
addNum(index) {
this.items[index].num++;
this.calcTotal();
},
// 合计 过滤掉没有选中的,将选中的所有商品价格都合计一起
calcTotal() {
const selectedItems = this.items.filter(item => item.selected);
this.total = 0;
selectedItems.forEach(item => {
this.total += item.num * item.price
})
this.total = parseFloat(this.total.toFixed(2));
},
// 商品所有勾选中了以后全选框为选中状态
// 商品全部不勾选中,全选框为没有选中状态
calcAllChecked() {
this.allChecked = this.items.every(item => item.selected);
}
}
})
// 自动调用合计 和 全选勾选状态
vm.calcTotal();
vm.calcAllChecked();
</script>
</body>