<template>
  <view>
    <!-- 多个复选框，带全选 -->
    <view>
      <checkbox-group class="block" @change="changeCheckbox">
        <view v-for="item in newDeviceManage" :key="item.id">
          <checkbox :value="String(item.id)" :checked="checkedArr.includes(String(item.id))" :class="{ checked: checkedArr.includes(String(item.id)) }"></checkbox>
          <text>{{ item.title }}</text>
        </view>
      </checkbox-group>
    </view>
    <view>
      <checkbox-group @change="allChoose">
        <label>
          <checkbox value="all" :class="{ checked: allChecked }" :checked="allChecked ? true : false"></checkbox>
          全选
        </label>
      </checkbox-group>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isChecked: false,
      newDeviceManage: [
        { id: 0, title: "选项一" },
        { id: 1, title: "选项二" },
        { id: 2, title: "选项三" },
        { id: 3, title: "选项四" },
        { id: 4, title: "选项五" },
        { id: 5, title: "选项六" },
        { id: 6, title: "选项七" },
        { id: 7, title: "选项八" },
        { id: 8, title: "选项九" },
        { id: 9, title: "选项十" },
      ],
      checkedArr: [], //复选框选中的值
      allChecked: false, //是否全选
    };
  },
  methods: {
    // 多选复选框改变事件
    changeCheckbox(e) {
      this.checkedArr = e.detail.value;
      // 如果选择的数组中有值，并且长度等于列表的长度，就是全选
      if (this.checkedArr.length > 0 && this.checkedArr.length == this.newDeviceManage.length) {
        this.allChecked = true;
      } else {
        this.allChecked = false;
      }
    },
    // 全选事件
    allChoose(e) {
      let chooseItem = e.detail.value;
      // 全选
      if (chooseItem[0] == "all") {
        this.allChecked = true;
        for (let item of this.newDeviceManage) {
          let itemVal = String(item.id);
          if (!this.checkedArr.includes(itemVal)) {
            this.checkedArr.push(itemVal);
          }
        }
      } else {
        // 取消全选
        this.allChecked = false;
        this.checkedArr = [];
      }
    },
  },
};
</script>

<style></style>
