vue 简单使用
程序员文章站
2022-03-03 23:29:25
...
<template>
<div v-if="cartList.length <= 0"> 购物车中没有商品</div>
<div v-else>
<table class="table">
<tr>
<th>选择</th>
<th>编号</th>
<th>名称</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
<tr v-for="(cart,index) in cartList" :key="index" >
<td>
<input type="checkbox" name="ids" :id="'id'+cart.id" :value="cart.id" v-model="ids" >
</td>
<td>{{cart.id}}</td>
<td>{{cart.name}}</td>
<td>{{cart.price.toFixed(2)}}</td>
<td>
<button @click="jian(cart.id,cart.price)">-</button>
{{cart.count}}
<button @click="jia(cart.id,cart.price)">+</button>
</td>
<td><a href="" @click.prevent="del(cart.id)" >删除</a> </td>
</tr>
<tr>
<td colspan="3">合计</td>
<td colspan="3">¥:{{getTotalPrice}}元</td>
</tr>
</table>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return {
ids:[],
amount:0,
cartList:[
{id:1,name:'aaa',price:1.10,count:1},
{id:2,name:'bbb',price:2.20,count:1},
{id:3,name:'ccc',price:3.30,count:1},
{id:4,name:'ddd',price:4.40,count:1},
{id:5,name:'eee',price:5.50,count:1}
]
}
},
methods:{
del(id){
let _this = this;
for(let i=0;i<_this.cartList.length;i++){
if(id===_this.cartList[i].id){
_this.cartList.splice(i,1);
}
}
},
jia(id){
let _this = this;
let cartList = _this.cartList;
for(let i=0;i<cartList.length;i++){
if(id===cartList[i].id){
cartList[i].count++;
}
}
},
jian(id){
let _this = this;
let cartList = _this.cartList
for(let i=0;i<cartList.length;i++){
if(id===cartList[i].id){
cartList[i].count--
if(cartList[i].count <= 0){
cartList[i].count=0;
}
}
}
}
},
computed:{
getTotalPrice:{
get(){
let _this= this;
let price= 0;
if(_this.ids.length>0){
for (let i =0;i<_this.ids.length;i++){
for(let j=0;j<_this.cartList.length;j++){
if(_this.ids[i]===_this.cartList[j].id){
price += (_this.cartList[j].price * _this.cartList[j].count)
}
}
}
}
_this.amount=price;
return _this.amount.toFixed(2);
}
}
}
}
</script>
<style>
.table,tr,td,th{
border: 1px solid black;
border-spacing: 0;
}
</style>
上一篇: 前端基础,伸缩盒布局小案例及总结