首页 > 其他分享 >el-table中实现列勾选和行勾选

el-table中实现列勾选和行勾选

时间:2024-03-29 13:44:05浏览次数:14  
标签:el false index 选和行 value 勾选 length let gunCode

功能展示:
el-table可以整列勾选,整行勾选,整行和整列勾选,全选取消,单个勾选

主要应用了el-table-column中的render-header方法,手动控制勾选状态
其中每行中的itemCheck${type},checked,isIndeterminate,以及 data中的 isCheck${type}, isIndeterminate${type}都是辅助参数。

目的是为了拿到已勾选的gunCode

代码展示:

  <div>
    <el-button @click="searchList"> 搜索</el-button>
    <el-table
      border
      class="customer-no-border-table"
      element-loading-text="数据正在加载中..."
      :row-class-name="tableRowClassName"
      :header-cell-style="{ background: '#E7F2FD', color: '#252525' }"
      style="width: 100%; border-top: 1px solid #409eff"
      ref="table"
      :data="tableData"
      :row-key="getRowKey"
      max-height="450px"
    >
      <el-table-column
        align="center"
        :resizable="false"
        :render-header="renderHeader"
      >
        <template #default="scope">
          <el-checkbox
            :indeterminate="scope.row.isIndeterminate"
            v-model="scope.row.checked"
            @change="select(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column type="index" label="序号" width="50" align="center">
      </el-table-column>
      <el-table-column
        v-for="column in columns"
        :key="column.prop"
        :prop="column.prop"
        :label="column.label"
        :resizable="false"
        :render-header="renderHeaderByType(column.type)"
        align="center"
        min-width="110"
      >
        <template slot-scope="scope">
          <el-checkbox
            v-if="scope.row[column.gunCode]"
            v-model="scope.row['itemCheck' + column.type]"
            @change="toggleCheck(scope.row, column.type)"
          ></el-checkbox>
          {{ scope.row[column.gunCode] }}
        </template>
      </el-table-column>
      <div slot="empty">
        <img
          alt="暂无数据"
          src="@/assets/nodata.png"
          style="width: 270px; height: 190px; margin-top: 80px"
        />
        <div style="font-size: 16px; color: #666666; margin-bottom: 80px">
          暂无数据
        </div>
      </div>
    </el-table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      columns: [
        { prop: "ipA1", label: "IP", gunCode: "gunCodeA1", type: "A1" },
        { prop: "ipB1", label: "IP", gunCode: "gunCodeB1", type: "B1" },
        { prop: "ipA2", label: "IP", gunCode: "gunCodeA2", type: "A2" },
        { prop: "ipB2", label: "IP", gunCode: "gunCodeB2", type: "B2" },
        { prop: "ipA3", label: "IP", gunCode: "gunCodeA3", type: "A3" },
        { prop: "ipB3", label: "IP", gunCode: "gunCodeB3", type: "B3" },
      ],
      //不同功率用到的变量
      isIndeterminateA1: false,
      isIndeterminateB1: false,
      isIndeterminateA2: false,
      isIndeterminateB2: false,
      isIndeterminateA3: false,
      isIndeterminateB3: false,
      isIndeterminate: false,
      isCheckA1: false,
      isCheckB1: false,
      isCheckA2: false,
      isCheckB2: false,
      isCheckA3: false,
      isCheckB3: false,
      isCheckAll: false,
      tableData: [],
      data: {},
    };
  },
  methods: {
    searchList() {
      this.reset();
      this.data = {
        gunList150: {
          gunTypeA: [],
          gunTypeB: [],
        },
        gunList400: {
          gunTypeA: [],
          gunTypeB: [],
          gunTypeC: [],
          gunTypeD: [],
        },
        gunList600: {
          gunTypeA1: [
            {
              uuid: null,
              gunCode: "FFF33A69",
              ip: "10.100.100.156",
              powerType: "01010256",
            },
            {
              uuid: null,
              gunCode: "FFF33A96",
              ip: "10.100.100.145",
              powerType: "01010289",
            },
          ],
          gunTypeB1: [
            {
              uuid: null,
              gunCode: "FFF33A04",
              ip: "10.100.100.125",
              powerType: "01010209",
            },
            {
              uuid: null,
              gunCode: "FFF33A05",
              ip: "10.100.100.125",
              powerType: "01010210",
            },
          ],
          gunTypeA2: [
            {
              uuid: null,
              gunCode: "FFF33A03",
              ip: "10.100.100.125",
              powerType: "01010203",
            },
            {
              uuid: null,
              gunCode: "FFF33A45",
              ip: "10.100.100.125",
              powerType: "01010205",
            },
          ],
          gunTypeB2: [
            {
              uuid: null,
              gunCode: "FFF11A03",
              ip: "10.100.100.121",
              powerType: "01010203",
            },
            {
              uuid: null,
              gunCode: "FFF33B03",
              ip: "10.100.100.126",
              powerType: "01010203",
            },
          ],
          gunTypeA3: [
            {
              uuid: null,
              gunCode: "FFF11A15",
              ip: "10.100.100.121",
              powerType: "01010278",
            },
            {
              uuid: null,
              gunCode: "FFF33B06",
              ip: "10.100.100.126",
              powerType: "01010287",
            },
          ],
          gunTypeB3: [
            {
              uuid: null,
              gunCode: "FFF11A04",
              ip: "10.100.100.121",
              powerType: "01010225",
            },
            {
              uuid: null,
              gunCode: "FFF33B01",
              ip: "10.100.100.126",
              powerType: "01010258",
            },
          ],
        },
      };
      this.formate600(this.data.gunList600);
    },
    // 1.格式化请求的数据并渲染
    formate150(value) {
      if (value) {
        let array = [];
        let a = value.gunTypeA.length;
        let b = value.gunTypeB.length;
        let c = a > b ? value.gunTypeA : value.gunTypeB;
        c.forEach((i, index) => {
          array.push({
            id: index,
            ipA: value.gunTypeA[index] ? value.gunTypeA[index].ip : "",
            ipB: value.gunTypeB[index] ? value.gunTypeB[index].ip : "",
            itemCheckA: false,
            itemCheckB: false,
            gunCodeA: value.gunTypeA[index]
              ? value.gunTypeA[index].gunCode
              : "",
            gunCodeB: value.gunTypeB[index]
              ? value.gunTypeB[index].gunCode
              : "",
            checked: false,
            isIndeterminate: false,
          });
        });
        this.tableData = array;
      } else {
        this.tableData = [];
      }
    },
    formate400(value) {
      if (value) {
        let array = [];
        let a = value.gunTypeA && value.gunTypeA.length;
        let b = value.gunTypeB && value.gunTypeB.length;
        let c = value.gunTypeC && value.gunTypeC.length;
        let d = value.gunTypeD && value.gunTypeD.length;
        let e = Math.max(a, b, c, d);
        console.log(e, "e");
        let f;
        if (e == a) {
          f = value.gunTypeA;
        } else if (e == b) {
          f = value.gunTypeB;
        } else if (e == c) {
          f = value.gunTypeC;
        } else if (e == d) {
          f = value.gunTypeD;
        }
        f.forEach((i, index) => {
          array.push({
            id: index,
            ipA: value.gunTypeA[index] ? value.gunTypeA[index].ip : "",
            ipB: value.gunTypeB[index] ? value.gunTypeB[index].ip : "",
            ipC: value.gunTypeC[index] ? value.gunTypeC[index].ip : "",
            ipD: value.gunTypeD[index] ? value.gunTypeD[index].ip : "",
            itemCheckA: false,
            itemCheckB: false,
            itemCheckC: false,
            itemCheckD: false,
            gunCodeA: value.gunTypeA[index]
              ? value.gunTypeA[index].gunCode
              : "",
            gunCodeB: value.gunTypeB[index]
              ? value.gunTypeB[index].gunCode
              : "",
            gunCodeC: value.gunTypeC[index]
              ? value.gunTypeC[index].gunCode
              : "",
            gunCodeD: value.gunTypeD[index]
              ? value.gunTypeD[index].gunCode
              : "",
            checked: false,
            isIndeterminate: false,
          });
        });
        this.tableData = array;
      } else {
        this.tableData = [];
      }
    },
    // formate600(value) {
    //   if (value) {
    //     let array = [];
    //     let a1 = value.gunTypeA1 && value.gunTypeA1.length;
    //     let b1 = value.gunTypeB1 && value.gunTypeB1.length;
    //     let a2 = value.gunTypeA2 && value.gunTypeA2.length;
    //     let b2 = value.gunTypeB2 && value.gunTypeB2.length;
    //     let a3 = value.gunTypeA3 && value.gunTypeA3.length;
    //     let b3 = value.gunTypeB3 && value.gunTypeB3.length;
    //     let e = Math.max(a1, b1, a2, b2, a3, b3);
    //     console.log(e, "e");
    //     let f;
    //     if (e == a1) {
    //       f = value.gunTypeA1;
    //     } else if (e == b1) {
    //       f = value.gunTypeB2;
    //     } else if (e == a2) {
    //       f = value.gunTypeA2;
    //     } else if (e == b2) {
    //       f = value.gunTypeB2;
    //     } else if (e == a3) {
    //       f = value.gunTypeA3;
    //     } else if (e == b3) {
    //       f = value.gunTypeB3;
    //     }

    //     f.forEach((i, index) => {
    //       array.push({
    //         id: index,
    //         ipA1: value.gunTypeA1[index] ? value.gunTypeA1[index].ip : "",
    //         ipB1: value.gunTypeB1[index] ? value.gunTypeB1[index].ip : "",
    //         ipA2: value.gunTypeA2[index] ? value.gunTypeA2[index].ip : "",
    //         ipB2: value.gunTypeB2[index] ? value.gunTypeB2[index].ip : "",
    //         ipA3: value.gunTypeA3[index] ? value.gunTypeA3[index].ip : "",
    //         ipB3: value.gunTypeB3[index] ? value.gunTypeB3[index].ip : "",
    //         itemCheckA1: false,
    //         itemCheckB1: false,
    //         itemCheckA2: false,
    //         itemCheckB2: false,
    //         itemCheckA3: false,
    //         itemCheckB3: false,
    //         gunCodeA1: value.gunTypeA1[index]
    //           ? value.gunTypeA1[index].gunCode
    //           : "",
    //         gunCodeB1: value.gunTypeB1[index]
    //           ? value.gunTypeB1[index].gunCode
    //           : "",
    //         gunCodeA2: value.gunTypeA2[index]
    //           ? value.gunTypeA2[index].gunCode
    //           : "",
    //         gunCodeB2: value.gunTypeB2[index]
    //           ? value.gunTypeB2[index].gunCode
    //           : "",
    //         gunCodeA3: value.gunTypeA3[index]
    //           ? value.gunTypeA3[index].gunCode
    //           : "",
    //         gunCodeB3: value.gunTypeB3[index]
    //           ? value.gunTypeB3[index].gunCode
    //           : "",
    //         checked: false,
    //         isIndeterminate: false,
    //       });
    //     });
    //     this.tableData = array;
    //   } else {
    //     this.tableData = [];
    //   }
    // },
    // 优化代码
    formate600(value) {
      if (value) {
        let array = [];
        let maxItemCount = 0;
        let maxItemKey = "";

        // 寻找最大数量的枪支类型
        Object.keys(value).forEach((key) => {
          if (value[key] && value[key].length > maxItemCount) {
            maxItemCount = value[key].length;
            maxItemKey = key;
          }
        });

        let gunTypes = value[maxItemKey];

        gunTypes.forEach((item, index) => {
          let newItem = {
            id: index,
            ipA1: value.gunTypeA1?.[index]?.ip || "",
            ipB1: value.gunTypeB1?.[index]?.ip || "",
            ipA2: value.gunTypeA2?.[index]?.ip || "",
            ipB2: value.gunTypeB2?.[index]?.ip || "",
            ipA3: value.gunTypeA3?.[index]?.ip || "",
            ipB3: value.gunTypeB3?.[index]?.ip || "",
            itemCheckA1: false,
            itemCheckB1: false,
            itemCheckA2: false,
            itemCheckB2: false,
            itemCheckA3: false,
            itemCheckB3: false,
            gunCodeA1: value.gunTypeA1?.[index]?.gunCode || "",
            gunCodeB1: value.gunTypeB1?.[index]?.gunCode || "",
            gunCodeA2: value.gunTypeA2?.[index]?.gunCode || "",
            gunCodeB2: value.gunTypeB2?.[index]?.gunCode || "",
            gunCodeA3: value.gunTypeA3?.[index]?.gunCode || "",
            gunCodeB3: value.gunTypeB3?.[index]?.gunCode || "",
            checked: false,
            isIndeterminate: false,
          };
          array.push(newItem);
        });

        this.tableData = array;
      } else {
        this.tableData = [];
      }
    },
    // 创建一个通用函数来处理列选择的过程
    handleColumnSelection(itemCheckProp, isCheckProp, isIndeterminateProp) {
      let length = this.tableData.filter((item) => item[itemCheckProp]).length;
      this[isCheckProp] =
        length === this.tableData.length && this.tableData.length > 0;
      this[isIndeterminateProp] = length < this.tableData.length && length > 0;
    },
    // 回显数据
    showOldData() {
      if (this.tableData) {
        // 回显每一列的全选框的状态
        const columns = ["A1", "B1", "A2", "B2", "A3", "B3"];
        columns.forEach((column) => {
          this.handleColumnSelection(
            `itemCheck${column}`,
            `isCheck${column}`,
            `isIndeterminate${column}`
          );
        });
        //回显每行全选半选的状态
        this.changeRowChecked();
        //回显总的全选框的全选/半选状态
        this.changeAllChecked();
      }
    },
    // 重置
    reset() {
      const columns = ["A1", "B1", "A2", "B2", "A3", "B3"];
      columns.forEach((column) => {
        this[`isCheck${column}`] = false;
        this[`isIndeterminate${column}`] = false;
      });
      this.isCheckAll = false;
      this.isIndeterminate = false;
    },

    getRowKey(row) {
      return row.id;
    },

    // 第一列的全选
    renderHeader(h) {
      return h("span", [
        h("el-checkbox", {
          on: {
            change: this.selectBox,
          },
          props: {
            value: this.isCheckAll,
            indeterminate: this.isIndeterminate,
          },
        }),
      ]);
    },
    selectBox(val) {
      this.isCheckAll = val;
      this.isIndeterminate = false;
      const columns = ["A1", "B1", "A2", "B2", "A3", "B3"];
      this.tableData.forEach((k) => {
        k.checked = val;
        k.isIndeterminate = false;
        columns.forEach((column) => {
          k[`itemCheck${column}`] = val;
          k[`isIndeterminate${column}`] = false;
        });
      });
      columns.forEach((column) => {
        this[`isCheck${column}`] = val;
        this[`isIndeterminate${column}`] = false;
      });
    },
    // 勾选行
    select(row) {
      const checked = row.checked;
      const columns = ["A1", "A2", "A3", "B1", "B2", "B3"];

      this.tableData.forEach((t) => {
        if (row.id === t.id) {
          columns.forEach((column) => {
            t[`itemCheck${column}`] = checked;
          });
          t.isIndeterminate = false;
        }
      });

      const length = this.tableData.length;
      const countChecked = (column) =>
        this.tableData.filter((item) => item[`itemCheck${column}`]).length;

      columns.forEach((column) => {
        const lengthColumn = countChecked(column);
        this[`isCheck${column}`] = lengthColumn === length && length > 0;
        this[`isIndeterminate${column}`] =
          lengthColumn > 0 && lengthColumn < length;
      });
      this.changeAllChecked();
    },

    //控制第一列全选框的状态
    changeAllChecked() {
      const array = this.tableData.reduce((acc, i) => {
        for (let j = 1; j <= 3; j++) {
          if (i["gunCodeA" + j]) {
            acc.push(i["itemCheckA" + j]);
          }
          if (i["gunCodeB" + j]) {
            acc.push(i["itemCheckB" + j]);
          }
        }
        return acc;
      }, []);

      this.isCheckAll = array.length > 0 && array.every((element) => element);
      this.isIndeterminate =
        !this.isCheckAll && array.some((element) => element);
    },

    renderHeaderByType(type) {
      return (h) => {
        return h("span", [
          h(
            "el-checkbox",
            {
              on: {
                change: () => this.selectByType(type),
              },
              props: {
                value: this[`isCheck${type}`],
                indeterminate: this[`isIndeterminate${type}`],
              },
            },
            `${type}枪编号`
          ),
        ]);
      };
    },
    selectByType(type) {
      const isCheck = `isCheck${type}`;
      const itemCheck = `itemCheck${type}`;

      this[isCheck] = !this[isCheck];
      this.tableData.forEach((item) => (item[itemCheck] = this[isCheck]));
      this.changeRowChecked();
      this.changeAllChecked();
    },
    // 控制行的选中状态
    changeRowChecked() {
      this.tableData.forEach((item) => {
        const checkedArray = [
          ...["A1", "A2", "A3", "B1", "B2", "B3"].map((column) => {
            return item[`gunCode${column}`] ? item[`itemCheck${column}`] : true;
          }),
        ];

        item.checked = checkedArray.every((element) => element);

        const array = [];
        for (let i = 1; i <= 3; i++) {
          ["A", "B"].forEach((prefix) => {
            const key = `gunCode${prefix}${i}`;
            const checkKey = `itemCheck${prefix}${i}`;
            if (item[key]) {
              array.push(item[checkKey]);
            }
          });
        }

        item.isIndeterminate = this.checkArray(array);
      });
    },
    // 枪编号多选框勾选事件
    toggleCheck(row, type) {
      const checkedArray = [
        ...["A1", "A2", "A3", "B1", "B2", "B3"].map((column) => {
          return row[`gunCode${column}`] ? row[`itemCheck${column}`] : true;
        }),
      ];

      row.checked = checkedArray.every((element) => element);

      const array = [];
      for (let i = 1; i <= 3; i++) {
        ["A", "B"].forEach((prefix) => {
          const key = `gunCode${prefix}${i}`;
          const checkKey = `itemCheck${prefix}${i}`;
          if (row[key]) {
            array.push(row[checkKey]);
          }
        });
      }

      row.isIndeterminate = this.checkArray(array);

      const list = this.tableData.filter((item) => item[`itemCheck${type}`]);
      this[`isCheck${type}`] =
        list.length === this.tableData.length && this.tableData.length > 0;
      this[`isIndeterminate${type}`] =
        list.length > 0 && list.length < this.tableData.length;
      this.changeAllChecked();
    },

    checkArray(arr) {
      const trueCount = arr.filter((element) => element === true).length;
      const falseCount = arr.length - trueCount;

      if (trueCount === arr.length) {
        return false;
      } else if (trueCount > 0 && falseCount > 0) {
        return true;
      } else {
        return false;
      }
    },
    saveData() {
      console.log(this.tableData, "this.tableData");
      let gunCode = [];

      const gunCodeKeys = ["A1", "A2", "A3", "B1", "B2", "B3"];

      this.tableData.forEach((i) => {
        gunCodeKeys.forEach((key) => {
          if (i[`itemCheck${key}`]) {
            gunCode.push(i[`gunCode${key}`]);
          }
        });
      });

      console.log("

标签:el,false,index,选和行,value,勾选,length,let,gunCode
From: https://www.cnblogs.com/hxy--Tina/p/18103685

相关文章

  • Jellyfish and EVA
    这道题目实在没有什么好的办法去描述状态空间,只能感性理解一下,等对概率的理解更深了再来吧。。。发现这是一道概率DP,而且满足拓扑序,我们直接倒序转移就好了设\(f_i\)表示从第\(i\)个点到第\(n\)个点的概率,我们发现当只有一条出边是非常好转移的,但是其他就不太行了我们遇到这种......
  • Ask HN: Recommended resources to learn the Linux kernel and OS theory?
     https://news.ycombinator.com/item?id=20809666 SorecentlyIdidacoupleofminorpatchesontheFreeBSDandNetBSDkernelsandplayedwithsomelinuxkernel.Itwasthefirsttimeinaafewyears,I'vebeenexcitedaboutprogramming.Unfortunat......
  • mysql 8 报错 ERROR 1872 (HY000): Slave failed to initialize relay log info struc
    在MySQL8中遇到错误1872(HY000):Slavefailedtoinitializerelayloginfostruct的问题通常与主从复制配置有关,可能是由于配置问题或者数据不一致导致的。以下是可能的解决方法:检查主从服务器配置:确保主服务器和从服务器的配置信息正确,包括server_id的设置,主服务......
  • 【期刊】人工智能评论 Artificial Intelligence Review
    Overview 概述ArtificialIntelligenceReviewisafullyopenaccessjournalpublishingstate-of-the-artresearchinartificialintelligenceandcognitivescience.《人工智能评论》是一本完全开放获取的期刊,发表人工智能和认知科学领域的最新研究。Publishes......
  • Sentinel 对分布式服务进行流量控制
    可以下载sentinel的jar包,用java-jar命令直接启动 默认端口就是8080,这里随便写一下演示,其他修改还是直接看Sentinel网站吧java-jar-Dserver.port=8080sentinel的jar包名.jar 对需要进行流量控制的服务进行依赖导入(这个依赖直接在父工程引入似乎无效,不知为何)<dependency>......
  • Aspose Cells 单元格 格式
    Aspose单元格格式编号///<summary>///单元格样式编号///0GeneralGeneral///1Decimal0///2Decimal0.00///3Decimal#,##0///4Decimal#,##0.00///5Currency$#,##0;$-#,##0///6Currency$#,##0;[Red]$-#,##0///7Currency$#,##0.00;$-#,#......
  • MybatisPlus多参数分页查询,黑马程序员SpringBoot3+Vue3教程第22集使用MP代替pagehelpe
    前言:视频来源1:黑马程序员SpringBoot3+Vue3全套视频教程,springboot+vue企业级全栈开发从基础、实战到面试一套通关视频来源2:黑马程序员最新MybatisPlus全套视频教程,4小时快速精通mybatis-plus框架创作理由:网上MP实现分页查询功能的帖子易读性太差,具体实现看下面。根据视频完成......
  • Qt自定义插件写Excel表格
    网上找到一个开源的Qt插件,下载下来,生成头文件和库文件,可以不依赖电脑是否安装Excel软件,是否有Excel驱动,可以直接输出excel文档https://github.com/dbzhang800/QtXlsxWriter/tree/master/src/xlsx#include"CopyAllFileThread.h"#include<QFileInfo>#include"LocalDb.h"#inc......
  • 《手把手教你》系列技巧篇(五十九)-java+ selenium自动化测试 - 截图三剑客 -上篇(详细教
    1.简介今天本来是要介绍远程测试的相关内容的,但是宏哥在操作服务器的时候干了件糊涂的事,事情经过是这样的:本来申请好的Windows服务器用来做演示的,可是服务器可能是局域网的,连百度都不能访问,宏哥想调试一下网络,禁用网卡,然后重启网卡,结果禁用后就连不上了。。。。就只能等服......
  • 《手把手教你》系列技巧篇(六十)-java+ selenium自动化测试 - 截图三剑客 -中篇(详细教程
    1.简介前面我们介绍了Selenium中TakeScreenshot类来截图,得到的图片是浏览器窗口内的截图。有时候,只截浏览器窗口内的图是不够的,而且TakeScreenshot截图只针对浏览器的web事件,假如你在运行脚本过程,windows上有一个其他软件弹出了一个购物的弹窗页面,这个时候就会干扰你......