Vue购物车案例(全选,反选,加入,删除,加减,总价,数量)
Posted 昨日的某某
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Vue购物车案例(全选,反选,加入,删除,加减,总价,数量)相关的知识,希望对你有一定的参考价值。
1.购物车效果图
2.代码展示
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
body{
font-size: 16px;
}
table {
width: 1200px;
}
ul li{
list-style: none;
}
table th {
width: 100px;
}
table td {
width: 200px;
text-align: center;
}
.m {
width: 20px;
}
.shang{
width: 30%;
float: left;
text-align: center;
}
</style>
<body>
<div id="app">
<div id="div">
<h1>商品</h1>
<div class="shang" v-for="item in list">
<ul>
<li>{{item.name}}</li>
<li><img v-bind:src="item.imgsrc" width="80px" height="80px" /></li>
<li>{{item.dan}}</li>
<li><button @click="addg(item)" v-bind:disabled="item.amit==1">加入购物车</button></li>
</ul>
</div>
</div>
<!-------------------->
<table>
<tr>
<th>全选:<input type="checkbox" :checked='isCheckedAll' @click='chang'></th>
<th>序列号</th>
<th>商品</th>
<th>图片</th>
<th>数量</th>
<th>单价(元)</th>
<th>金额(元)</th>
<th>操作</th>
</tr>
<tr v-for="(item,index) in shopping">
<th><input type="checkbox" v-model="item.checked" /></th>
<th>{{index+1}}</th>
<th>{{item.name}}</th>
<th><img v-bind:src="item.imgsrc" width="80px" height="80px" /></th>
<th>
<button @click='jian(item)'>-</button>
<span></span>{{item.age}}
<button @click='jia(item)'>+</button>
<th>{{item.dan }}</th>
<th>{{(item.age*item.dan).toFixed(2) }}</th>
<th @click="del(index)">删除</th>
</tr>
<!--<h2>总价:{{getSum()}}</h2>-->
<tr>
<th>总价:<span v-text="getSum"></span></th>
<th>计件:{{jSut()}}</th>
</tr>
</table>
</div>
</body>
<script src="../js/vue.js">
</script>
<script type="text/javascript">
new Vue({
el: "#app",
data: {
list: [],
shopping: []
},
mounted() {
//fetch跟ajax一样,配合promise函数
fetch('tupian.json')
//把传过来的数据转为json对象
.then(respose => respose.json())
.then(reust => {
//reust.data 是json里面data,存到数组里面去
this.list = reust.data
})
},
methods: {
addg(list) {
let p = this.shopping.find(value => value.id == list.id)
list.amit--
console.log(p)
if(p) {
p.age++ //点击的时候总数量件-1
} else {
let {
name,
imgsrc,
checked,
dan,
id
} = list;
this.shopping.push({
checked,
id,
dan,
name,
imgsrc,
age: 1 // 点击加入购物车产品数量为1
})
}
},
//减
jia(index) {
index.age++
},
jian(index) {
if(index.age != 0) {
index.age--
}
},
//全选
chang() {
var flag = !this.isCheckedAll
this.shopping.forEach(item => item.checked = flag)
},
//选中删除
del(index) {
if(this.shopping[index].checked == true) {
this.shopping.splice(index, 1)
}
},
//计件
jSut() {
var sut = 0
for(var i in this.shopping) {
var item = this.shopping[i]
if(item.checked == true) {
sut += this.shopping[i].age
}
}
return sut
}
},
computed: {
//总价
getSum() {
var sum = 0
this.shopping.forEach(item => {
if(item.checked == true) {
sum += item.age * item.dan
}
})
return sum.toFixed(2);
},
//全选
isCheckedAll() {
return this.shopping.every(item => item.checked)
}
},
})
</script>
</html>
以上是关于Vue购物车案例(全选,反选,加入,删除,加减,总价,数量)的主要内容,如果未能解决你的问题,请参考以下文章