实战 element-plus 级联选择器(Cascader)+企微部门架构

先看效果 :

1、部门架构数据来源于企业微信;

2、部门层级关系的展现和勾选;

具体实现:

1、组件官方文档

http://element-plus.org/zh-CN/component/cascader.html

级联选择器组件要求的数据格式:

重点:了解清楚数据格式

2、后端写法(php)

php 复制代码
   // 递归查询负责的子部门(给 elementplus 组件用的)
    public static function getSubdepartments2($sub_id, $all_departments) {
        $output = array();
        foreach ($all_departments as $department) {
            if ($department['parent_id'] == $sub_id) {
                $arr = ['value'=>$department['id'],'label'=>$department['name']];
                // 继续判断是否有下一级
                $subdepartments = self::getSubdepartments2($department['id'], $all_departments);
                if (!empty($subdepartments)) {
                    // 返回所有子部门
                    // $arr['children'] = $subdepartments;
                    // 只返回两级
                    $arr[] = $subdepartments;
                }
                $output[] = $arr;
            }
        }
        return $output;
    }
     

    
   public function department($id=194){
      $row = Department::where('parent_id',$id)->field('id as value,name as label')->select();
      $alldeptlist = Department::select();
      foreach($row as &$val){
          // 查询是否有子部门
          $children = self::getSubdepartments2($val['value'],$alldeptlist);
            if(!empty($children)){
                $val['children'] = $children;
            }
      }
       if($row){
             $this->success('查询成功',$row);
         }else{
             $this->error('找不到数据!');
         }
   }

递归方法说明

另外一个注意点:

递归有可能返回空数组,可能会出现"空级联"的 bug,如下面这位老铁的文章提及到的:

那么我们在调用递归结果时,只需要判断是否为空(如上图 348 行代码),空就不要添加 children 对象了。

相关推荐
梦想的旅途218 小时前
企业微信API:企业微信接口能实现哪些功能?
企业微信
梦想的旅途21 天前
企微 API 二次开发:结合 AI 打造考勤打卡与报表智能分析系统
人工智能·企业微信
鱼日先生2 天前
办公聊天软件接入 Hermes Agent 实录(一):企业微信 WebSocket 长连接 + Dify 知识库问答
企业微信·dify·ai agent·大模型应用·hermes agent
梦想的旅途22 天前
企微私域自动化:客户全生命周期 SOP 策略与配置实战
运维·自动化·企业微信
梦想的旅途22 天前
企业微信销售自动化:线索分配与超时预警
小程序·自动化·企业微信
梦想的旅途22 天前
企微社群裂变实战:自动化群接龙与活动打卡系统搭建
运维·自动化·企业微信
梦想的旅途22 天前
企微私域 AI 创作:文案生成与 AI 配图自动化发布实战
人工智能·自动化·企业微信
梦想的旅途22 天前
企业微信API实战:Python自动化消息推送
java·前端·python·自动化·企业微信
梦想的旅途23 天前
企业微信API实战:外部群定时群发与SOP自动推送指南
企业微信
梦想的旅途23 天前
企业微信自动化实战:客户资料自动修改与备注同步
运维·自动化·企业微信