上代码(vue环境下)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>普通版购物车</title>
<link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css">
<style>
.container .row table tr td{
vertical-align: middle;
}
</style>
</head>
<body>
<div id="app">
<div class="container">
<div class="row">
<table class="table table-bordered">
<caption class="h2 text-center text-danger">购物车</caption>
<!--第一行-->
<tr>
<td>全选 <input type="checkbox" @change="checkAll" v-model="selectAll"></td>
<td>商品</td>
<td>单价</td>
<td>数量</td>
<td>小计</td>
<td>操作</td>
</tr>
<!--第二行和第三行-->
<tr v-for="(item,index) in arr">
<td><input type="checkbox" v-model="item.isSelected" @change="checkOne"></td>
<td>
<img :src="item.productCover" alt="">
</td>
<td>{{item.productPrice}}</td>
<td><input type="number" v-model="item.productCount"></td>
<td>{{item.productPrice*item.productCount | a(2)}}</td>
<td><button class="btn-danger" @click="remove(index)">删除</button></td>
</tr>
<!--最后一行-->
<tr>
<!--合并单元格-->
<td colspan="6">总价格:¥{{sum() | a(2)}}</td>
</tr>
</table>
</div>
</div>
</div>
<script src="../node_modules/vue/dist/vue.js"></script>
<script src="../node_modules/axios/dist/axios.js"></script>
<script>
let vm = new Vue({
el: '#app',
data: {
arr:[],
selectAll:true,
},
created(){
this.getCont();
},
methods:{
getCont(i){
axios.get('./carts.json').then(val=>{
//console.log(val.data);//
this.arr=val.data;
//console.log(this.arr);
})
},
remove(i){
this.arr=this.arr.filter((item,index)=>{
return i!==index;//如果传进来的索引和过滤的索引相同就留下了
})
},
checkAll(){//想改视图,就往数据上改
this.arr.forEach(item=>item.isSelected=this.selectAll)
},
checkOne(){
// 只要数组中有一个是false,则selectAll就是false;所有的都是true,才返回true;
this.selectAll = this.arr.every(item=>item.isSelected)
},
sum(){
return this.arr.reduce((prev,next)=>{
if(!next.isSelected){return prev};
return prev+next.productPrice*next.productCount;
},0)
}
},
filters:{//过滤器,管道符
a(val,count){
console.log(val);
console.log(count);
return '¥'+val.toFixed(count);
}
},
});
</script>
</body>
</html>
复制代码
carts.json
[
{
"isSelected": true,
"productCover": "https://img10.360buyimg.com/cms/s80x80_jfs/t6094/107/710811867/382815/4d54717/592bf165N755a88f0.jpg",
"productName": "深入浅出Node.js",
"productInfo": "颜色:Node.js学习",
"productPrice": 57.8,
"productCount": 3
},
{
"isSelected": true,
"productCover": "https://img10.360buyimg.com/cms/s80x80_jfs/t6094/107/710811867/382815/4d54717/592bf165N755a88f0.jpg",
"productName": "深入浅出Node.js",
"productInfo": "颜色:Node.js学习",
"productPrice": 57.8,
"productCount": 3
}
]
复制代码