// 在表单中使用

<el-form-item label="级联">
  <el-cascader
    placeholder="请选择"
    @change="cascaderChange"
    :props="{
      checkStrictly: false,
      emitPath: false,
      multiple: true,
    }"
    :value="form.cascader"
    :options="options"
    clearable
    ref="cascaderRef"
  />
</el-form-item>

// 涉及到的方法
methods:{
  cascaderChange(value) {
    this.getValue(this.form.cascader, 'cascaderRef', 'form', value)
  },
  getValue (initVal, refName, editRuleForm, value) {
    var nodes = this.$refs[refName].getCheckedNodes();
    if (nodes.length == 0) {
      this[editRuleForm].cascader = [];
      return;
    }
    const editArray = []
    // 新增的值
    const newData = []
    const cancelData = []

    nodes.forEach(item => {
      const find = initVal.findIndex(id => id === item?.path[1] && item.checked) !== -1
      const findCancel = value.findIndex(id => id === item?.path[1] && item.checked) === -1
      if (findCancel || !item.checked) {
        cancelData.push({ ...item, checked: false })
      } else if (find) {
        // 已经选中的一级
        editArray.push({ parent: item?.path[0], child: item?.path[1] })
      } else if (item.checked) {
        // 已经选择的新的
        newData.push(item)
      }
    })
    const lastNode = newData[newData.length - 1]
    // 最后操作的节点,首级存在在已经在的值内
    if (editArray.findIndex(i => i.parent === lastNode?.path?.[0]) !== -1) {
      const newBranch = this[editRuleForm].cascader.filter(id => {
        return editArray.findIndex(i => i.child === id && lastNode?.path?.[0] === i.parent) === -1
      })
      newBranch.unshift(lastNode?.path?.[1])
      this[editRuleForm].cascader = newBranch
    } else {
      const newBranch = this[editRuleForm].cascader.filter(id => {
        return cancelData.findIndex(item => item.path[1] === id) === -1 && nodes.findIndex(item => item.path[1] === id) !== -1
      })
      if (lastNode?.path?.[1]) {
        newBranch.unshift(lastNode.path[1])
      }
      this[editRuleForm].cascader = newBranch
    }
  },
}

效果图

Logo

前往低代码交流专区

更多推荐