css样式如下:
*{
margin: 0;
padding: 0;
}
section{
width: 1000px;
margin: auto;
display: flex;
justify-content: flex-start;
flex-wrap: wrap;
border: 1px solid #000;
}
.box{
width: 24%;
height: 300px;
text-align: center;
border: 1px solid #000;
}
.box img{
width: 200px;
height: 200px;
}
p{
margin-top: 10px;
}
button{
margin-left: 5px;
}
span{
color: red;
}
table{
width: 1000px;
margin: auto;
margin-bottom: 50px;
}
.name{
width: 500px;
}
td{
text-align: center;
}
.small{
width: 100px;
height: 50px;
}
<script src="vue.js"></script>
<script>
var app= new Vue({
el:'#root',
data:{
list:[],
num:[],
sum:''
},
methods:{
f1(i){
let arr=this.list;
let arrNum=this.num;
let flag=true;
for (let j = 0; j < arrNum.length; j++) {
if(arrNum[j].Id==arr[i].Id){
flag=false;
arrNum[j].shu+=1
break;
}
}
if(flag){
this.num.push({
Id:arr[i].Id,
title:arr[i].title,
img:arr[i].img_list_url,
price:arr[i].price,
checked:false
,shu:1
})
}
},
plus(i){
this.num[i].shu==1?this.num.splice(i,1):this.num[i].shu--
}
},
computed:{
all(){
let nuaAll=0
this.num.forEach((v,i)=>{
if(v.checked){
nuaAll+=v.price*v.shu
}
})
return this.sum=nuaAll
}
}
})
fetch("./goodList.json").then(res=>{
return res.json()
}).then(res=>{
console.log(res);
app.list=res
})
</script>
当然需要引入vue.js
<div id="root">
<h1 style="text-align:center">购物车</h1>
<section>
<div v-for="item,i in list" class="box">
<img :src="item.img_list_url" alt="">
<p>{{item.title}}</p>
<p><span>${{item.price}}</span><button @click="f1(i)">加入购物车</button></p>
</div>
</section>
<table border="1" cellpadding="30">
<tr>
<th>选中</th>
<th class="name">名称</th>
<th>图片</th>
<th>价格</th>
<th>数量</th>
</tr>
<template v-if="num.length>0">
<tr v-for="v,i in num">
<td><input type="checkbox" v-model="v.checked"></td>
<td>{{v.title}}</td>
<td><img :src="v.img" alt="" class="small"></td>
<td>{{v.price}}</td>
<td><button @click="plus(i)">-</button>{{v.shu}}<button @click="v.shu++">+</button></td>
</tr>
</template>
<tr>
<td></td>
<td colspan="4" class="sum">总价格:{{all}}元</td>
</tr>
</table>
</div>