vue十二:vue基础之购物车案例

 

商品数据准备:

datalist: [
  {name: "商品1", price: 10, number: 1, id: "1"},
  {name: "商品2", price: 20, number: 2, id: "2"},
  {name: "商品3", price: 30, number: 3, id: "3"}
]

 

实现选中商品,计算总金额

1.给每个商品加个复选框,选中后将商品加到一个list里面

 

2.实时计算金额

定义一个计算的函数,当checkgroup状态改变的时候,函数会自动重新计算

 

3.实现全选功能

3.1根据全选按钮的选中状态判断商品是否改为选中状态

 

3.2.根据商品的选中状态,判断全选按钮是否为选中状态

 

4.实现加减按钮,并且对商品增加或减少

4.1实现加,点击的时候number自增即可

 

4.2实现减点击时候number自减,减致0时,不再减

<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<meta http-equiv='X-UA-Compatible' content='ie=edge'>
<script src='./vue.js'></script>
<title></title>
</head>
<body>
<div id='app'>
<input type="checkbox" @change="handleChang" v-model="isAllChecked">
<ul>
<li v-for="data in datalist">
<input type="checkbox" v-model="checkgroup" :value="data" @change="handleLiChange">
{{ data }}
<button @click="handleClick(data)">-</button>
{{ data.number }}
<button @click="data.number++">+</button>
</li>
</ul>
{{ checkgroup }}
<p>选中商品总金额为:{{ getSum() }}</p>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
checkgroup: [],
datalist: [
{name: "商品1", price: 10, number: 1, id: "1"},
{name: "商品2", price: 20, number: 2, id: "2"},
{name: "商品3", price: 30, number: 3, id: "3"}
],
isAllChecked: false
},
methods: {
handleClick(data) {
var number = data.number--;
if (number === 0) {
data.number = 0
}
},
handleLiChange() {
// 根据商品的选中状态,判断全选按钮是否为选中状态
if (this.checkgroup.length === this.datalist.length) {
this.isAllChecked = true
} else {
this.isAllChecked = false
}
},
handleChang() {
// 如果选中了全选按钮,则将所有商品都置位选中状态
if (this.isAllChecked) {
this.checkgroup = this.datalist
} else {
this.checkgroup = []
}
},
getSum() {
// 计算选中商品的总金额
var sum = 0;
for (var i in this.checkgroup) {
sum += this.checkgroup[i].number * this.checkgroup[i].price
}
return sum
}
}

})
</script>
</body>
</html>

 

posted @ 2021-01-19 21:38  向前走。  阅读(611)  评论(0编辑  收藏  举报