<!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>
#box {
width: 1200px;
margin: 0 auto;
}
table {
width: 1200px;
margin: 0 auto;
border: 1px solid #000;
border-collapse: collapse;
table-layout: fixed;
text-align: center;
}
td {
border: 1px solid #000;
}
img {
width: 50px;
}
</style>
</head>
<body>
<!-- shoppingTrolley -->
<div id="box">
<input @change="Allchecked" type="checkbox" v-model="isAll" />全选/全不选
<table>
<tr v-for="(obj,i) in arr">
<td><input @change="Itemchecked" type="checkbox" v-model="checklist" :value="obj" /></td>
<td>{{obj.id}}</td>
<td><img :src="obj.src" /></td>
<td>{{obj.name}}</td>
<td>{{obj.price}}</td>
<td>
<button @click="obj.count--" :disabled="obj.count==1">-</button>
{{obj.count}}
<button @click="obj.count++" :disabled="obj.count==obj.limit">+</button>
</td>
<td><button @click="deleteItem(i,obj.id)">删除</button></td>
</tr>
</table>
<div>总金额:{{computedSum}}</div>
</div>
<script src="../vue.global.js"></script>
<script>
Vue.createApp({
data() {
return {
isAll: false,
checklist: [],
arr: [
{ "id": 1001, "name": '可口可乐', "price": 2.5, "count": 1, "limit": 5, "src": "img/logo.png" },
{ "id": 1003, "name": '百事可乐', "price": 2.5, "count": 1, "limit": 10, "src": "img/logo.png" },
{ "id": 1011, "name": '非常可乐', "price": 2.3, "count": 1, "limit": 5, "src": "img/logo.png" },
{ "id": 1012, "name": '天府可乐', "price": 2.3, "count": 1, "limit": 15, "src": "img/logo.png" },
{ "id": 1013, "name": '地府可乐', "price": 2.3, "count": 1, "limit": 5, "src": "img/logo.png" },
{ "id": 1014, "name": '阳间可乐', "price": 2.3, "count": 1, "limit": 20, "src": "img/logo.png" },
{ "id": 1015, "name": '阴间可乐', "price": 2.3, "count": 1, "limit": 5, "src": "img/logo.png" },
]
}
},
methods: {
Allchecked() {
if (this.isAll) {
this.checklist = this.arr;
} else {
this.checklist = [];
}
},
Itemchecked() {
if (this.checklist.length == this.arr.length) {
this.isAll = true;
} else {
this.isAll = false;
}
},
deleteItem(i, id) {
this.arr.splice(i, 1);
this.checklist = this.checklist.filter(item => item.id !== id);
}
},
computed: {
computedSum() {
var total = 0;
this.checklist.forEach(obj => {
total += obj.price * obj.count;
})
return total;
},
}
}).mount("#box")
</script>
</body>
</html>
一个简洁的vue实现购物车功能
最新推荐文章于 2024-06-11 12:41:07 发布