vue全选反选demo

<template>
  <div>
    <div class="xuanze">
      <label><input type="checkbox" v-model="all" @change="allfn">全选</label>

      <br><br>

      <div class="store" v-for="(store,index1) in stores">
        <label><input type="checkbox" v-model="store.all" @change="storefn(index1)">{{store.name}}</label>
        <ul>
          <li v-for="(item,index2) in store.product"><label><input type="checkbox" v-model="item.xuanze" @change="productfn(index1,index2)">{{item.id}}</label></li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      all: false,

      stores: [
        {
          name: '草泥马一号店',
          all: false,
          sellength: 0,
          product:[ 
            {
              id: 1,
              xuanze: false,
            },
            {
              id: 2,
              xuanze: false,
            },
            {
              id: 3,
              xuanze: false,
            },
          ]
        },
        {
          name: '草泥马二号店',
          all: false,
          sellength: 0,
          product:[
            {
              id: 1,
              xuanze: false,
            },
            {
              id: 2,
              xuanze: false,
            },
            {
              id: 3,
              xuanze: false,
            },
          ]
        },
      ]
    }
  },
  methods: {
    allfn: function(){
      for (let i = 0;i < this.stores.length ;i++ )
      {
        let store = this.stores[i];
        store.sellength = this.all ? store.product.length : 0;
        store.all = this.all;
        for (let j = 0;j < store.product.length ;j++ )
        {
          store.product[j].xuanze = this.all;
        }
      }
    },
    storefn: function(index1){
      let store = this.stores[index1];
      let res = store.all;
      store.sellength = res ? store.product.length : 0;
      for (let i = 0;i < store.product.length ;i++ )
      {
        store.product[i].xuanze = res;
      }
      this.all = true;
      for (let j = 0;j < this.stores.length ;j++ )
      {
        if (!this.stores[j].all)
        {
          this.all = false;
          break;
        }
      }
    },
    productfn: function(index1,index2){
      let store = this.stores[index1];
      let product = store.product[index2];
      store.sellength = product.xuanze ? store.sellength+1:store.sellength-1;
      store.all = store.sellength == store.product.length;
      this.all = true;
      for (let j = 0;j < this.stores.length ;j++ )
      {
        if (!this.stores[j].all)
        {
          this.all = false;
          break;
        }
      }
    }
  }
}
</script>

<style scoped>
  .xuanze{
    margin: 100px;
  }
  .store{
    border-bottom: 1px solid red;
    margin-bottom: 5px;
  }
  ul{
    margin-left: 20px;
  }
</style>

  

原文地址:https://www.cnblogs.com/caonima-666/p/6830326.html