<body>
<style>
* {
list-style: none;
box-sizing: border-box;
padding: 0;
margin: 0;
}
body {
text-align: center;
}
ul {
width: 80%;
height: 500px;
margin: 0 auto;
display: flex;
flex-wrap: wrap;
text-align: center;
margin-top: auto 0;
line-height: 2;
}
ul img {
width: 100px;
height: 100px;
margin-top: 30px;
}
ul li {
width: 25%;
border: 1px solid rgb(15, 15, 15);
}
ul li p {
font-weight: 600;
font-size: 14px;
}
ul li span {
color: red;
font-size: 16px;
font-weight: 600;
}
table {
width: 80%;
height: 30px;
margin: 50px auto;
border-collapse: collapse;
}
table tr td img {
width: 50px;
height: 50px;
}
</style>
<script src='https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js'></script>
<div id='app'>
<h1>{{message}}</h1>
<!-- 所有商品列表 -->
<ul>
<li v-for='item,index in goodList'>
<div>
<img :src="item.img_list_url" alt="">
<p>{{item.title}}</p>
<span>${{item.price}}</span>
<button @click="jiaru(item)">加入购物车</button>
</div>
</li>
</ul>
<table border="1">
<thead>
<tr>
<th>选中</th>
<th>名称</th>
<th>图片</th>
<th>价格</th>
<th>数量</th>
</tr>
</thead>
<tr v-for='item,index in shopCar'>
<td><input type="checkbox" :value="item.Id" v-model="selected"></td>
<td>{{item.title}}</td>
<td><img :src='item.img_list_url'></td>
<td>${{item.price}}</td>
<td>
<button @click='reduce(index)'> - </button>
{{item.count}}
<button @click='()=>{item.count++; $forceUpdate();}'> + </button>
</td>
</tr>
<th colspan="5">选中的商品总价:{{total}}</th>
</table>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
message: '购物车',
goodList: [], // 所有商品列表
shopCar: [], // 购物车列表
selected : [] // 购物车中选中的商品列表
},
computed: {
// 计算总价
total(){
let sum = 0;
this.selected.forEach(id=>{
var goods = this.shopCar.find(goods=>{
return goods.Id == id
})
if(goods){
sum += goods.price * goods.count
}
})
return sum
}
},
methods: {
// 添加购物车函数
jiaru(item) {
// 判断购物车中是否有这个商品
var goods = this.shopCar.find(goods=>{
return goods.Id == item.Id
})
if(goods){
// 如果有, 商品数量+1, 并更新视图
goods.count ++;
this.$forceUpdate()
}else{
// 不存在, 初始化商品数量为1,并添加到购物车列表
item.count = 1;
this.shopCar.push(item)
}
},
// 商品数量减少
reduce(index){
if(this.shopCar[index].count > 1){
// this.shopCar[index].count --;
// this.$forceUpdate(); //强制刷新
var goods = this.shopCar[index]
goods.count --
this.$set(this.shopCar, index, goods)
}else{
if(confirm("是否要删除商品")){
// 找到购车这个商品的id
var goodId = this.shopCar[index].Id;
// 判断这个id在已选中列表中是否存在, 如果存在,说明这个商品是选中状态,先把它的id删掉, 取消选中
for(let i = 0; i < this.selected.length; i++ ){
if(this.selected[i] == goodId){
this.selected.splice(i, 1);
break;
}
}
// 把商品从购物车列表删掉
this.shopCar.splice(index,1)
}
}
}
},
created() {
//对象已经创建, 请求数据
fetch("./goodList.json").then(res => {
return res.json()
}).then(data => {
this.goodList = data.slice(0, 8)
})
}
})
</script>
</body>
goodList.json