微信小程序实现单选、全选、反选、取消全选功能

2024-01-18 20:43:47 浏览数 (2)

实现效果
源代码
代码语言:javascript复制
<!-- 循环单选 -->
	<view
	  class="parkNotice-email"
	  v-for="(item2, index2) in dataList2"
	  :key="index2"
	  @click="checkChange(index2)"
	>
	  <view class="img">
	    <image
	      :src="
	        item2.check
	          ? localImg.park.checkIcon
	          : localImg.park.uncheckedIcon
	      "
	    ></image>
	  </view>
	  <view class="title">
	    {{ item2.fileName   "."   item2.fileFormat }}
	  </view>
	</view>
<!-- 全选 -->
	<view class="selected">
	  <span class="image">
	    <view @click="allSelected(index)">
	      <image
	        :src="
	          allChecked
	            ? localImg.park.checkIcon
	            : localImg.park.uncheckedIcon
	        "
	      ></image>
	    </view>
	  </span>
	  <view class="title">全选</view>
	</view>
代码语言:javascript复制
 allChecked: true, //全选,true为勾选状态,false为未勾选状态

//获取装修指南数据
  getDecorateList() {
    // this.isLoad2 = true;
    //businessType:4 装修指南
    getDecorateGuide({ businessType: 4, current: 1, rowCount: 10 })
      .then((res) => {
        let data = res.data.rows;
        data.forEach((value) => {
          this.dataList2.push({
            check: true, //true为勾选状态,false为未勾选状态
            fileName: value.fileName,
            fileFormat: value.fileFormat,
            id: value.id,
          });
        });
        this.isLoad2 = false;
      })
      .catch((error) => {
        console.log(error);
      });
  },
    
  //单选
    checkChange(index) {
      this.dataList2[index].check = !this.dataList2[index].check;
      //当勾选全选后,取消一个单选,全选则消失(这段的逻辑我之前有错误)
     //不是比较全部单选勾选的长度,而是判断所有的单选是否都勾选为true
      for (var i = 0, length = this.dataList2.length; i < length; i  ) {
        if (this.dataList2[i].check == false) {
          this.allChecked = false;
          return;
        }
      }
      this.allChecked = true;
    },
    
    //全选
    allSelected() {
    //勾选全选,则所有的单选都勾选
      if (this.allChecked == true) {
        this.dataList2.forEach((value) => {
          value.check = false;
        });
      } else {
        this.dataList2.forEach((value) => {
          value.check = true;
        });
      }
      this.allChecked = !this.allChecked;
    },

错误代码展示回顾

代码语言:javascript复制
//单选
 checkChange(index) {
 for (var i = 0; i < this.dataList2.length; i  ) {
     if (this.dataList2[i].check == true) {
          this.allChecked == true;
        } else {
           this.allChecked == false;
        }
   }
 }

0 人点赞