基本购物车
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="vue.js"></script>
</head>
<body>
<div id="app">
<table>
<thead>
<td>
id
</td>
<td>
name
</td>
<td>
price
</td>
<td>
count
</td>
<td>
<input type="checkbox" v-model="chooseAll" @change="handleAll"> {{chooseAll}}
</td>
</thead>
<tr v-for="good in goodList">
<td>{{good.id}}</td>
<td>{{good.name}}</td>
<td>{{good.price}}</td>
<td>
<button @click="handleJian(good)">-</button>
{{good.count}}
<button @click="good.count++">+</button>
</td>
<td><input type="checkbox" :value="good" v-model="chooseGoods" @change="handleOne">
</td>
</tr>
</table>
{{chooseGoods}}
{{getTotalPrice()}}
</div>
</body>
<script>
const app = Vue.createApp(
{
data() {
return {
goodList: [
{id: '1', name: '小汽车', price: 150000, count: 2},
{id: '2', name: '鸡蛋', price: 2, count: 1},
{id: '3', name: '饼干', price: 10, count: 6},
{id: '4', name: '钢笔', price: 15, count: 5},
{id: '5', name: '脸盆', price: 30, count: 3},
],
chooseGoods: [],
chooseAll: false
}
},
methods: {
getTotalPrice() {
let total = 0
// 方式1:es6 的 of 循环
for (item of this.chooseGoods) {
total += item.price * item.count
}
//方式2:数组的循环:循环计算选中的商品价格
this.chooseGoods.forEach(function (v, i) {
total += v.price * v.count
})
return total
},
handleAll() {
if (this.chooseAll) {
this.chooseGoods = this.goodList
} else {
this.chooseGoods = []
}
},
handleOne() {
this.chooseAll = (this.chooseGoods.length == this.goodList.length)
},
handleJian(good) {
if (good.count > 0){
good.count--
}
}
}}
).mount('#app')
</script>
</html>
本文作者:Sherwin
本文链接:https://www.cnblogs.com/sherwin1995/p/16826000.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步