el-cascader添加全选,设置全选、不选、半选_el-cascader全选-程序员宅基地

技术标签: 前端开发  vue  elementui  vue.js  javascript  

在这里插入图片描述
直接就可以用了


<template>
  <div ref="riskReportQueryList" class="riskReportQueryList">
    <div style="background:#fff;padding:10px;">
      <div style="font-size:16px;height:40px;line-height:45px;padding-left:20px;border-bottom:1px solid #DCDFE6;font-weight: 700;">
        查询
      </div>
      <el-form ref="ruleForm" :model="ruleForm" label-width="120px" style="background: #fff; padding: 20px 0 0px;font-weight:400;">
        <el-row>
          <el-col :span="5">
            <el-form-item label="选择模型" prop="riskPhase">
              <el-cascader v-model="ruleForm.value" clearable filterable :options="options2" :props="{  multiple: true}" :collapse-tags="true" placeholder="请选择" @change="selectHandle">
                <template slot-scope="{ node, data }">
                  <span>{
    {
     data.label }}</span>
                  <span v-if="!node.isLeaf"> ({
    {
     data.children.length }}) </span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="padding-left:40px;">
            <el-button type="primary" @click="defaultSelectSomeone">选中某项</el-button>
            <el-button type="primary" @click="defaultSelectAll">全选</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
    
  name: "riskReportQueryList",
  // import引入的组件需要注入到对象中才能使用PopupTreeInput
  components: {
     Treeselect },
  props: [""],
  data() {
    
    // 这里存放数据
    return {
    
      lastSelectedList: [], // 上次选中的数据
      oneDimensionalList: [], //  源数据平铺成一级节点
      ruleForm: {
    
        value: [],
      }, //查询 传参
      options2: [
        {
    
          value: "全选",
          label: '全选',
        },
        {
    
          value: 1,
          label: '东南',
          children: [{
    
            value: 2,
            label: '上海',
          }, {
    
            value: 3,
            label: '江苏',
          }, {
    
            value: 4,
            label: '浙江',
          }]
        }, {
    
          value: 5,
          label: '西北',
          children: [{
    
            value: 6,
            label: '陕西',
          }, {
    
            value: 7,
            label: '新疆维吾尔族自治区',
            children: [{
    
              value: 8,
              label: '陕西',
            }, {
    
              value: 9,
              label: '新疆维吾尔族自治区',
            }],
          }],
        }, {
    
          value: 10,
          label: '西北',

        }],
      options2Number: 0,
      selectAllStatusList: [],
      test: "",
    };
  },
  // 监听属性 类似于data概念
  computed: {
    },
  // 监控data中的数据变化
  watch: {
    
    test: {
    
      deep: true, // deep: true  // 可以深度检测到 test 对象的属性值的变化
      handler(newV) {
    
        this.test = newV;
      },
    },
  },
  // 生命周期 - 创建完成(可以访问当前this实例)
  created() {
     },
  // 生命周期 - 挂载完成(可以访问DOM元素)
  mounted() {
    
    // 全选的数据
    this.oneDimensionalList = []
  },
  // 方法集合
  methods: {
    
    getTreeList(list) {
    
      let _this = this;
      for (let i = 0; i < list.length; i++) {
    
        let a = list[i];
        if (a.label !== '全选') {
    
          this.oneDimensionalList.push(list[i])
        }
        if (a.children && a.children.length > 0) {
    
          let res = _this.getTreeList(a.children);
          if (res) {
    
            return res;
          }
        }
      }
    },
    defaultSelectSomeone() {
    
      this.ruleForm.value = [['1', '2']];
    },
    defaultSelectAll() {
    
      this.selectHandle([['全选']])
    },
    judgetAllSelected(node) {
    
      // 判断是否是全选,也就是看已选择的选中中包不包含"全选"
      console.log("node11111111", node);
      let isAllSelected = false
      for (let i = 0; i < node.length; i++) {
    
        if (node[i][0] === '全选') {
    
          isAllSelected = true
          break;
        }
      }
      return isAllSelected
    },
    loopSelectData(list, parentNode = []) {
    
      list.length > 0 && list.forEach(e => {
    
        let pNode = [...parentNode]; // 注意这里必须是深拷贝,否则会由于引用类型赋值的是地址(指针),导致parentNode在pNode更新时,同时被更新
        if (e.children && e.children.length > 0) {
    
          pNode.push(e.value)// 1 11
          this.loopSelectData(e.children, pNode)
        } else {
    
          if (parentNode.length > 0) {
    
            this.ruleForm.value.push([...parentNode, e.value])
          } else {
    
            this.ruleForm.value.push([e.value])
          }
        }
      })
    },
    checkIsAddAllSelected() {
    
      // 通过dom获取到控制全选,不选,半选的样式
      let label1 = document.querySelector('.el-cascader-panel').querySelector('.el-cascader-menu__wrap').querySelectorAll("li")[0].querySelectorAll("label")[0]
      let span1 = document.querySelector('.el-cascader-panel').querySelector('.el-cascader-menu__wrap').querySelectorAll("li")[0].querySelectorAll("label")[0].querySelectorAll("span")[0]

      // 获取所有的数据
      let list = this.options2; // 原始数据列表
      if (this.oneDimensionalList.length === 0) {
    
        this.getTreeList(list) // 把所有的父子级平铺成一个一级列表
      }

      let origin = [...this.oneDimensionalList].filter(item => !item.children)//获取所有的叶子节点
      let nowList = [...this.ruleForm.value].filter(item => item[0] !== '全选')

      // 半选时, 如果有之前选过全选,要把全选过滤掉
      if (origin.length > nowList.length && nowList.length != 0) {
    
        this.ruleForm.value = this.ruleForm.value.filter(item => item[0] !== '全选')
        //设置半选样式,setTimeout可以解决样式渲染不上的问题
        setTimeout(function () {
    
          label1.className = "el-checkbox"
          span1.className = "el-checkbox__input is-indeterminate"
        }, 1)
      } else if (nowList.length == 0) {
    
        //不选时, 如果有之前选过全选,要把全选过滤掉
        this.ruleForm.value = this.ruleForm.value.filter(item => item[0] !== '全选')
        label1.className = "el-checkbox"
        span1.className = "el-checkbox__input"
      } else {
    
        // 当所有的数据都选择时, 要自动把全选勾选上  最后这种是:origin.length == nowList.length
        if (this.ruleForm.value[0] && this.ruleForm.value[0][0] !== '全选') {
    
          this.ruleForm.value = [['全选'], ...this.ruleForm.value]
          label1.className = "el-checkbox"
          span1.className = "el-checkbox__input is-checked"
        }
      }
    },
    // 选择级联选择器
    async selectHandle(e = []) {
    
      console.log("node1111", e);
      this.ruleForm.value = []

      // 选中的数据格式: [['全选'], [1, 2], [1, 3], [1, 4],[5, 6], [5, 7, 8],5, 7, 9],[10]]
      let list = this.options2//级联选择器的数据
      let current = []; // 获取当前选中的哪个数据,因为element文档中没有获取当前选中数据的方法,只能通过上次选中的数据和这次选中的数据进行比较来获取

      // 选中的所有数据list和上一次选中的list进行比较
      if (e.length >= this.lastSelectedList.length) {
    
        let keys = this.lastSelectedList.map(item => JSON.stringify(item))
        current = e.filter(item => !keys.includes(JSON.stringify(item)))
        console.log('选中某项', current);
      } else {
    
        // 取消选中
        let keys = e.map(item => JSON.stringify(item))
        current = this.lastSelectedList.filter(item => !keys.includes(JSON.stringify(item)))
        console.log('取消选中', current);
      }
      // 根据element的选中数据格式, 每一个选项都是一个列表, 列表第一项为父级value, 第二项为选中的子级value, ...以此类推
      const currentValue = current.length > 0 ? current[0][0] || '' : ''
      if (currentValue === '全选') {
    
        if (this.judgetAllSelected(e)) {
    
          this.loopSelectData(list)//获取全选时回显的数据
        } else {
    
          this.ruleForm.value = []//不选
        }
      } else {
    
        this.ruleForm.value = e//半选
      }
      // 根据当前选择的数据(不包括全选)和全选时所有的数据--进行对比
      this.checkIsAddAllSelected();

      this.lastSelectedList = this.ruleForm.value; // 保存上一次的选择结果
      this.changeHandle();
    },
    changeHandle() {
    
      // 这里是处理成自己需要的数据格式, 需要把全选的这一选项过滤掉
      // 原始选择的数据格式 [['全选'], [1, 2], [1, 3], [1, 4],[5, 6], [5, 7, 8],5, 7, 9],[10]]
      console.log('changeHandle: ', this.ruleForm.value);
    },
  },
};
</script>
<style lang='scss' >


</style>
<style lang='scss' scoped>
 ::v-deep .el-form-item__label {
    
  font-weight: 400 !important;
}
</style>


注:本文是根据别人的文章,进行的整理和改写,主要是为了做一个记录,方便以后查看,有看不懂的地方,可以去原文查看,链接为vue+elementUI(el-cascader)实现全选功能_szjSmiling的博客-程序员宅基地_el-cascader 全选,这个大神真的很牛

我在此基础上加了半选状态,嘻嘻,欢迎来指教!

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/ingenuou_/article/details/127685601

智能推荐

Linux下用VS Code调试makefile工程_使用vs code 和makefile_奔跑吧猴哥的博客-程序员宅基地

{ "tasks": [ { "type": "cppbuild", "label": "C/C++: g++ build active file", "command": "make", "args": [ ], "options": { "cwd": "${fileDirname}" ..._使用vs code 和makefile

OOP-面向对象程序设计课程项目_oop项目-程序员宅基地

16级计算机科学与技术, 网络工程同学的课程项目文档, 已经上传至网盘: https://pan.baidu.com/s/1rEFKstAjqIuQtZD0GTUuYA_oop项目

《Shell 编程》13_Shell 脚本规范及调试-程序员宅基地

《Shell 编程》13_Shell 脚本规范及调试标签(空格分隔): Shell文章目录《Shell 编程》13_Shell 脚本规范及调试13.1 Shell 脚本规范13.1.1 Shell 脚本基本规范13.1.2 Shell 脚本变量命名及引用变量规范13.1.3 Shell 函数的命名及函数定义规范13.1.4 Shell 脚本(模块)命名规范13.1.5 Shell 脚本代码框...

Java.lang.NoSuchMethodException 解决_java getmethod() java.lang.nosuchmethodexception: _敏姐儿的博客-程序员宅基地

问题解决Lombok注意在某一些项目里面会造成失效问题 需要注掉 在手动添加get set方法反射机制使用class.getMethod("String",Class) 中没有规定反射属性加上相应的属性类型即可 列如:class.getMethod("String",Double.Class)如有其他方法 多多指教...._java getmethod() java.lang.nosuchmethodexception: com.unionpay.uock.magpie.d

一文读懂Java 11的ZGC为何如此高效-程序员宅基地

导读:GC是大部分现代语言内置的特性,Java 11 新加入的ZGC号称可以达到10ms 以下的 GC 停顿,本文作者对这一新功能进行了深入解析。同时还对还对这一新功能带来的其他可能性做了展望。ZGC是否可以达到该性能目标,请看高可用架构志愿者翻译的文章。Java 11的新功能已经完全冻结,其中有些功能绝对非常令人兴奋,本文着重介绍ZGC。Java 11包...

IOS日期时间转JSON格式计算显示NAN问题-程序员宅基地

问题是这样的:因为做的是一个需要时间转换的,即24小时内转换为小时、分、秒,所以用后台返回的数据(2020-09-27 18:34)转为时间戳和现在的时间戳进行比较。但是通过这种(2020-09-27 18:34)格式转换出来,在IOS手机上显示为NaN,原因是IOS系统不支持这种格式,所以需要将其转换为(2020/09/27 18:34)这种格式。export function formatTime(dataTime){ let time = dataTime.replace(/\-/g, "/

随便推点

Unity中的`SetPositionAndRotation()`_unity设置rotation_忽然602的博客-程序员宅基地

是Unity中的一个方法,用于同时设置物体的位置和旋转。它可以在不必分别调用和属性的情况下,直接设置物体的位置和旋转。_unity设置rotation

linux查看jvm参数命令,通过命令查看jvm参数-程序员宅基地

4.1 查看堆详细信息:jmap -heap pid4.2 查看当前堆中对象统计信息: jmap -histo pid4.3 jmap -dump:format=b,file=dumpFileName pid监控GC的工具分为2种:命令行工具和图形工具,图形工具可以进入jdk的bin目录下打开Jconcole.exe 下面先说命令行工具,在已经设置好java环境变量的情况下,可以在任意地方打开命令..._查看jvm参数的命令

图(无向图)的BFS和DFS遍历_无向图的dfs和bfs-程序员宅基地

二刷数据结构,总结归纳一下树/图的遍历区别以前一直分不清,学的稀里糊涂的…这次系统的认真看了数据结构,实现了代码,总结了几点纳一下树/图的遍历。(使用的是王道408复习教材)建议看一下我上一篇博客,实现的Dijkstra,收益匪浅,用时1h40m(编码小白很是欣慰==)好了,接下来总结一下:首先,图没有根结点,不像树的遍历,可以从root开始,图的遍历一般要指定开始的结点,而且图的任意顶点都可能和其余顶点相连接,所以为避免重复访问,设置bool visited[]数组记录结点是否被访问,同时,_无向图的dfs和bfs

开票系统 文化服务器,开票服务器系统_愚者为聪的博客-程序员宅基地

开票服务器系统 内容精选换一换若已有连接后端服务器超过请求超时时间没有请求传输后,ELB会将其断开。根据负载均衡器与后端服务器链接的协议不同,系统默认超时时间也不同,系统默认的超时时间如下。TCP协议:默认超时时间为300s。UDP协议:默认超时时间为10s。HTTP协议:默认请求超时时间为60s。如果您需要使用毕昇编译器,则需要先在服务端安装毕昇编译器。毕昇编译器基于开源LLVM开发,并进行了优...

图文详解YUV420数据格式_yuv420 multi-planar-程序员宅基地

YUV格式有两大类:planar和packed。对于planar的YUV格式,先连续存储所有像素点的Y,紧接着存储所有像素点的U,随后是所有像素点的V。对于packed的YUV格式,每个像素点的Y,U,V是连续交*存储的。YUV,分为三个分量,“Y”表示明亮度(Luminance或Luma),也就是灰度值;而“U”和“V” 表示的则是色度(Chrominance或Chroma),作用..._yuv420 multi-planar

android--杂项_wh_xia_jun 微信-程序员宅基地

工具,曾经想用Genymotion这个比较强大的模拟器,用比较老的版本的微信,最多,就是跑起来微信,登陆后总是失败,不晓得微信收集到什么信息,不让微信在模拟器当中运行。环境准备:红米3 andriod 6.0.1 miui 8.7.12 开发版xposed 3.1.5版本微信版本7.0.4用红米手机 要获取root权限红米手机安装xopsed 成功模拟..._wh_xia_jun 微信

推荐文章

热门文章

相关标签