console
<style>
.add_box {
width: 750px;
padding: 50px;
box-sizing: border-box;
text-align: center;
border: 1px solid gray;
background-color: #ffb142;
margin: 0 auto
}
table {
margin: 0 auto;
margin-top: 50px;
}
tr {
line-height: 50px;
}
th {
background-color: #cc8e35;
}
td {
background-color: #ffb142;
text-align: center;
}
td:first-child {
text-align: left;
padding-left: 20px;
}
</style>
<body>
<div id="app">
<section class="add_box">
<input type="text" placeholder="商品名称" v-model="nameValue">
<input type="number" placeholder="商品单价" v-model="priceValue" @input="priceValue<=0?priceValue=1:priceValue">
<input type="number" v-model="numValue" @input="numValue<=0?numValue=1:numValue">
<button @click="addItem">添加到购物车</button>
</section>
<cart :cartlist="shopList" @changelist="changeList"></cart>
</div>
<template id="cart">
<table width="800" border="1" cellspacing="0" cellpadding="5">
<tr>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>总价</th>
<th>操作</th>
</tr>
<tr v-for="item in tempList" :key="item.id">
<td><input type="checkbox" @click="checkClick(item.id)" :checked="item.isSelect">{{item.name}}</td>
<td><p>单价:{{item.price}}</p></td>
<td><input type="number" v-model="item.num" @input="input(item.id)"></td>
<td><p>总价:{{total(item)}}</p></td>
<td><button @click="del(item.id)">删除</button></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td><p>总价:{{allTotal}}</p></td>
<td></td>
</tr>
</table>
</template>
<script>
let app = new Vue({
el:"#app",
data:{
shopList:[{
id:1,name:"饭团",price:5,num:10,isSelect:false,
},{
id:2,name:"车仔面",price:7,num:5,isSelect:false,
},
{
id:3,name:"车仔面",price:7,num:5,isSelect:false,
}],
nowId:3,
nameValue:"",
priceValue:1,
numValue:1
},
methods:{
addItem(){
if(this.nameValue!="" && this.priceValue!="" && this.numValue!=0){
if(isNaN(Number(this.priceValue)) || Number(this.priceValue)<0 || Number(this.numValue)<0){
alert("请正确输入正确数字[非字母,非负数]");
}else{
this.shopList.push({
id:++this.nowId,
name:this.nameValue,
price:this.priceValue,
num:this.numValue,
isSelect: false,
})
this.nameValue="";
this.priceValue=this.numValue=1
}
}else{
alert("非法参数,请正确填写");
}
},
changeList(list){
this.shopList=list;
}
},
components:{
cart:{
template:"#cart",
props: ['cartlist'],
data() {
return {
tempList:JSON.parse(JSON.stringify(this.cartlist)),
checkList:[],
}
},
methods:{
total(item){
return item.price*item.num
},
del(id){
this.tempList = this.tempList.filter(item=>{
return item.id!=id
})
},
checkClick(id){
this.tempList.some(item=>{
if(item.id==id){
item.isSelect=!item.isSelect
return true;
}
})
},
input(id){
this.tempList.some(item=>{
if(item.id==id){
item.num<=0?item.num=1:item.num;
return true;
}
})
}
},
computed:{
allTotal(){
let count=0
this.tempList.filter(item=>{return item.isSelect}).forEach(item=>{
count += item.price*item.num
})
return count;
}
},
watch:{
tempList:{
handler(){
this.$emit("changelist",this.tempList)
},
deep:true
}
}
}
}
})
</script>
</body>