Cascader级联选择器多选时获取所有选中状态的节点和半选状态的节点的数组集合

发布时间 2023-09-19 09:15:26作者: 0510忠邦
<!-- Cascader级联选择器组件 -->
<el-cascader
  v-model="query.companyList"
  ref="searchCompanyCascaderRef"
  :options="permissionCompanyTree"
  :props="companyCascaderProp"
  collapse-tags
  clearable
></el-cascader>
// 树图数据
permissionCompanyTree: [
  {
    id: 2272,
    code: "610000000000",
    name: "陕西公安厅",
    children: [
      {
        id: 2271,
        code: "612400000000",
        name: "安康公安",
        children: [
          {
            id: 2273,
            code: "612428000000",
            name: "安康市镇坪县公安局",
            children: [
              {
                id: 2274,
                code: "612428010000",
                name: "镇坪县公安局国保大队",
                children: null
              }, {
                id: 2276,
                code: "612428020000",
                name: "镇坪县公安局国保大队2",
                children: null
              }
            ]
          }
        ]
      }
    ]
  }
]

// 级联选择器配置项
companyCascaderProp: {
  multiple: true,
  label: "name",
  value: "code",
  emitPath: false
},
// 获取所有选中状态的节点和半选状态的节点的数组集合
fn() {
  // 获取已勾选的叶子节点
  const leafNodeList = this.$refs.searchCompanyCascaderRef.getCheckedNodes(true)
  // 定义list用于存放父节点code
  let codeList = []
  // 先将勾选中的叶子节点的code存入到codeList中
  leafNodeList.forEach(item => {
    codeList.push(item.value)
  })
  // 根据勾选节点往上查找其父节点, 先判断父节点的勾选状态为勾选或者半选, 再判断list中是否已有该父节点的code, 如果没有, 则将父节点的code存入数组中
  for (let i = 0; i < leafNodeList.length; i++) {
    // 调用递归方法
    this.getCodeList(codeList, leafNodeList[i])
  }
  console.log(codeList)
},

// 递归查找并获取级联选择器勾选状态和半勾选状态的节点的code数组集合
getCodeList(list, node) {
  // 若父节点存在 && 父节点勾选状态为勾选或者半选 && codeList中没有该父节点的code
  if ((node.parent) && (node.parent.checked || node.parent.indeterminate) && (!list.includes(node.parent.value))) {
    // 将符合条件的节点的code存入到codeList中
    list.push(node.parent.data.code)
    // 以leafNodeList[i]为准, 调用递归函数并继续往下查找符合条件的父节点
    this.getCodeList(list, node.parent)
  }
},

勾选状态如下:
image

通过fn方法获取的codeList如下:
image