用vue写表格实现数量的加减

<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>

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值