<template>
<div>
<div class="app">
<table>
<thead>
<tr>
<th>序号</th>
<th>名称</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
</tr>
</thead>
<tbody>
<tr v-for="({pname,price,count,max},index) in products" :key="index">
<td>{{index+1}}</td>
<td>{{pname}}</td>
<td>{{price}}</td>
<td>
<button @click="products[index].count--" :disabled="count==1" >-</button>
<span class="count" >{{count}}</span>
<button @click="products[index].count++" :disabled="count==max">+</button>
</td>
<td>{{price*count}}</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="6">总价格:{{total()}}--{{sum}}--{{sumad}}</td>
</tr>
</tfoot>
</table>
</div>
</div>
</template>
<script>
export default {
//计算属性第三种写法:reduce写法
computed:{
sumad(){
//+=的意思:每次遍历 都在原先总和的基础上加本次遍历的结果
return this.products.reduce((s,p)=>s+p.price*p.count,0);
},
},
//计算属性第二种写法:不加小括号也可以触发的写法
//计算属性:函数不用小括号也能触发 适合不带参数的函数
//固定:存放在这里的方法 使用时不用括号会自动触发
//下面是另一种计算总数的写法
//事件要手动才能触发 computed是自动触发的,所以click这样的事件不能放在computed中
computed:{
sum(){
let s=0;
this.products.forEach((p) => (s+=p.price*p.count));
return s;
}
},
//计算属性第一种写法
methods:{
//遍历products把每个商品的单价*数量累加到一起
total(){
let s=0;
this.products.forEach((p) => (s+=p.price*p.count));
return s;
}
},
data() {
return {
products: [
{ pname: "橘子", price: 7, count: 10, max: 11 },
{ pname: "葡萄", price: 8, count: 10, max: 60 },
{ pname: "西瓜", price: 9, count: 10, max: 50 },
{ pname: "荔枝", price: 10, count: 10, max: 70 },
{ pname: "草莓", price: 11, count: 10, max: 80 },
],
};
},
};
</script>
<style lang="scss" scoped>
table{
// 合并
border-collapse: collapse;
.count{
display: inline-block;
margin: 0 5px;
min-width: 35px;
text-align: center;
}
th,td{
border: 1px solid grey;
padding: 3px 30px;
}
}
</style>