element-ui的el-tree组件实现单选功能及选择子节点,获取所有父级节点或选中所有父级节点

el-tree是不支持单选的,可以通过选中事件进行处理,实现单选

实现单选

<el-tree
    ref="tree"
    :data="treeData"
    :props="defaultProps"
    :show-checkbox //显示选择框
    :check-on-click-node="true" //点击节点的时候选中节点
    :check-strictly="true" //在显示复选框的情况下,严格的遵循父子不互相关联的做法
     node-key="id" 
    @check="treeCheck" //选中后事件,在此事件中实现单选
    >
</el-tree>
methods: {
  treeCheck(data, list) {
    //data 该节点所对应的对象、list 树目前的选中状态对象
    //选中事件在选中后执行,当lis中有两个选中时,使用setCheckedKeys方法,选中一个节点
    //单选实现
    if (list.checkedKeys.length > 0) {
      //单选实现
      this.$refs.tree.setCheckedKeys([data.id])
    } else {
      //取消当前选中节点
      this.$refs.tree.setCheckedKeys([])
    }
  }
}

获取选中子节点的所有父级节点

methods: {
  treeCheck(data, list) {
    let thisNode = this.$refs.tree.getNode(data.id),
        keys = [data] // 获取已勾选节点的key值
     if (thisNode.checked) {
      // 当前节点若被选中
      for (let i = thisNode.level; i > 1; i--) {
        // 当前子节点选中,取消勾选父节点
        this.$refs.tree.setChecked(thisNode.parent, false)
        // 判断是否有父级节点
        if (!thisNode.parent.checked) {
          // 父级节点未被选中,则将父节点替换成当前节点,往上继续查询,并将此节点key存入keys数组
          thisNode = thisNode.parent
          keys.unshift(thisNode.data)
        }
      }
    }
    console.log(keys, 'keys++++++++++++++)
  }
}

点击子节点选中其所有父级节点

methods: {
  // 选中子节点,默认选中父节点
  checkeTree(data, list) {
    let thisNode = this.$refs.tree.getNode(data.id), // 获取当前节点
        keys = this.$refs.tree.getCheckedKeys() // 获取已勾选节点的key值
    if (thisNode.checked) { // 当前节点若被选中
      for (let i = thisNode.level; i > 1; i--) {
        // 当前子节点选中,取消勾选父节点
        this.$refs.tree.setChecked(thisNode.parent, false)
        // 判断是否有父级节点
        if (!thisNode.parent.checked) { // 父级节点未被选中,则将父节点替换成当前节点,往上继续查询,并将此节点key存入keys数组
          thisNode = thisNode.parent 
          keys.push(thisNode.data.id)
        }
      }
    }

    this.$refs.tree.setCheckedKeys(keys) // 将所有keys数组的节点全选中
  }
}

到此结束。

猜你喜欢

转载自blog.csdn.net/weixin_43743175/article/details/127759401