<template>
  <div class="login">
    <div class="item" v-for="(item,index) in dataList" :key="index">
      <input @change="change(index,item.checked)" type="checkbox" :checked="item.checked" />
      {{item.name}},单价{{item.price}}个数{{item.num}}
    </div>
    <div class="item">
      <input type="checkbox" @change="changeAll" :checked="allChecked" />
      全选,总数量{{count}}总价格{{money}}
    </div>
  </div>
</template>
<script>
export default {
  name: "login",
  data() {
    return {
      dataList: [
        { id: 1, name: "苹果", price: 4, num: 4 },
        { id: 2, name: "香蕉", price: 3, num: 2 },
        { id: 3, name: "梨", price: 3, num: 2 },
        { id: 4, name: "西红柿", price: 2, num: 11 },
      ],
      allChecked: false,
      count: 0,
      money: 0,
    };
  },
  methods: {
    changeAll() {
      this.count = 0;
      this.money = 0;
      for (var i = 0; i < this.dataList.length; i++) {
        this.$set(this.dataList[i], "checked", false);
      }
      if (this.allChecked) {
        this.allChecked = false;
        this.count = 0;
        this.money = 0;
      } else {
        this.allChecked = true;
        for (var j = 0; j < this.dataList.length; j++) {
          this.count += Number(this.dataList[j].num);
          this.money +=
            Number(this.dataList[j].num) * Number(this.dataList[j].price);
          this.$set(this.dataList[j], "checked", true);
        }
      }
    },
    change(index, checked) {
      this.count = 0;
      this.money = 0;
      console.log(checked,887)
      if (!checked) {
        this.$set(this.dataList[index], "checked", true);
      } else {
        this.$set(this.dataList[index], "checked", false);
      }
      this.$nextTick(() => {
        for (var j = 0; j < this.dataList.length; j++) {
          if (this.dataList[j].checked) {
            this.count += Number(this.dataList[j].num);
            this.money +=
              Number(this.dataList[j].num) * Number(this.dataList[j].price);
          }
        }
        if (this.dataList.every((item) => item.checked == true)) {
          this.allChecked = true;
        } else {
          this.allChecked = false;
        }
      });
    },
  },
};
</script>
<style lang="scss">
.login {
  margin: 100px;
}
.item {
  display: flex;
}
</style>
posted on 2020-08-04 11:43  小白学前端  阅读(596)  评论(0编辑  收藏  举报