<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>购物车</title>
</head>
<style>
table,
table tr th,
table tr td {
border: 1px solid;
border-collapse: collapse;
}
table tr th,
table tr td {
width: 120px;
height: 40px;
text-align: center;
}
</style>
<body>
<div id="app">
<table>
<tr>
<th colspan="6">商品列表</th>
</tr>
<tr>
<th>商品编号</th>
<th>商品图片</th>
<th>商品名称</th>
<th>商品单价</th>
<th>商品描述</th>
<th>功能</th>
</tr>
<tr v-for="(item,index) in goods" :key="index">
<td>{{item.id}}</td>
<td><img :src="item.pic" width="50px" /></td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>{{item.info}}</td>
<td>
<button @click="del(index)">删除</button>
<button @click="go(item)">上车</button>
</td>
</tr>
</table>
<p></p>
<table>
<tr>
<th colspan="8">购物车列表</th>
</tr>
<tr>
<th>选择</th>
<th>商品编号</th>
<th>商品图片</th>
<th>商品名称</th>
<th>商品单价</th>
<th>数量</th>
<th>小计</th>
<th>功能</th>
</tr>
<tr v-for="(item,index) in newgoods">
<td><input type="checkbox" v-model="item.selected"></td>
<td>{{item.id}}</td>
<td><img :src="item.pic" width="60px" /></td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>{{item.num}}</td>
<td>{{item.total}}</td>
<td>
<button @click="carDel(index)">删除</button>
</td>
</tr>
<tr v-if="newgoods.length==0">
<td colspan="8">暂无商品</td>
</tr>
</table>
<button @click="selAll">全选</button>
<button @click="selRev">反选</button>
总价:{{sum}}
</div>
</body>
</html>
<script src="./js/vue.js"></script>
<script>
new Vue({
el: '#app',
data: {
goods: [
{ id: 1001, pic: './img/aa.jpg', name: '卫龙辣条', price: 1.9, info: '很香狠辣' },
{ id: 1002, pic: './img/dd.jpg', name: '米多奇曲奇', price: 2.8, info: '好吃才是正经事' },
{ id: 1003, pic: './img/zz.jpg', name: '烤馍片', price: 9.9, info: '香香脆脆' },
{ id: 1004, pic: './img/aa.jpg', name: '旺旺雪饼', price: 23.8, info: '咔咔脆' },
],
newgoods: [],
isAll: true
},
watch:{
newgoods:{
deep:true,
handler(nv){
console.log(nv);
let isTrue = true
nv.forEach(item=>{
if(item.selected == false){
this.isAll = false
isTrue = false
}
if(isTrue){
this.isAll = true
}
})
}
}
},
methods: {
del(index){
this.goods.splice(index,1);
},
carDel(index){
this.newgoods.splice(index,1)
},
go(item) {
let on = true
this.newgoods.forEach(i =>{
if(i.id == item.id){//判断商品id是否一样,一样++
i.num++
i.total = (i.num * i.price).toFixed(2)
on = false
}
})
if(on){
let li = JSON.parse(JSON.stringify(item))
li.num = 1
li.total = li.num * li.price
li.selected = false
this.newgoods.push(li)
}
},
selAll(){
this.isAll = !this.isAll
this.newgoods.forEach(item=>{
item.selected = this.isAll
})
},
selRev(){
this.newgoods.forEach(item=>{
item.selected = !item.selected
})
}
},
computed:{
sum(){
let tt=0
this.newgoods.forEach(item=>{
if(item.selected){
tt+=item.num*item.price
}
})
return tt.toFixed(2)//返回两位小数点
}
}
})
</script>