简单的写了一下购物车 没有写样式 写的不好请大佬们多指教
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
[v-cloak]{
display: none;
}
</style>
<!-- vue框架 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- axios -->
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.0/axios.js"></script>
<style>
table {
border-collapse: collapse;
}
th,td {
border: 1px solid black;
padding: 20px;
}
</style>
</head>
<body>
<div id="app" v-cloak>
<table class="cart">
<tr>
<th> <input type="checkbox" @click="allck" v-model="allChecked">全选</th>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
<th>操作</th>
</tr>
<tr v-for="(item,index) in goods"> <!--定义商品是否被选中-->
<td> <input type="checkbox" @click="ck(item.id)" :checked="cart1.indexOf(item.id)!=-1"></td>
<td>{{item.name}}</td>
<td class="flex">¥{{item.price}}</td>
<td>
<!-- 购物车数量加减 -->
<button @click="--item.count" :disabled="item.count===1?true:false">-1</button>
{{item.count}}
<button @click="++item.count">+1</button>
</td>
<td>¥{{item.count*item.price}}</td>
<td><button @click="click1(index)">删除</button></td>
</tr>
<tr>
<td colspan="6">总计: {{sumprice}}</td>
</tr>
</table>
</div>
<script>
new Vue({
el: "#app",
data() {
return {
cart1:[],
allChecked: false,
sum: 0,
goods: [{
id: 1,
name: "请问",
count: 1,
price: "1999"
},
{
id: 2,
name: "完全",
count: 2,
price: "1999"
},
{
id: 3,
name: "按顺序",
count: 1,
price: "1999"
},
{
id: 4,
name: "而得出",
count: 3,
price: "1999"
},
{
id: 5,
name: "温度",
count: 5,
price: "1999"
}
],
}
},
methods: {
//根据索引删除
click1(index) {
this.goods.splice(index, 1)
},
//单选
ck(id) {
let res=this.cart1.indexOf(id)
res===-1?this.cart1.push(id):this.cart1.splice(res,1)
this.allChecked=this.goods.length==this.cart1.length
},
//全选
allck() {
if(!event.currentTarget.checked){
//取消全选
this.cart1=[]
}else{
this.goods.forEach((item,index)=>{
this.cart1.push(item.id)
})
}
}
},
computed: {
//计算总价的方法
sumprice() {
let sum = 0
this.goods.forEach((item,index) => {
let res=this.cart1.indexOf(item.id)
if(res!=-1){
//总价
sum += item.count * item.price
}
});
return sum;
}
}
})
</script>
</body>
</html>
效果图: