記錄一個部門及部門人員選擇的功能,效果如下:
組件用到了uni-ui的級聯選擇uni-data-picker
開發文檔:uni-app官網
組件要求的數據格式如下:
后端使用的是fastadmin,需要用到fastadmin自帶的tree類生成部門樹 ,后端代碼如下:
/*** 獲取部門及員工數據(樹形結構)適用于uni-ui的uni-data-picker*/public function getDepartmentAndStaff(){// 獲取所有部門(含層級關系)$departments = Db::name('wecom_department')->field('id, name, parent_id')->order('id ASC')->select();// 構建部門樹$tree = new Tree();$tree->init($departments,'parent_id',' ');$treeList = $tree->getTreeList($tree->getTreeArray(210), 'name'); // 從頂級部門開始// 處理每個部門下的員工$result = [];foreach ($treeList as $dept) {$deptData = ['text' => $dept['name'], // 前端顯示名稱'value' => 'dept_' . $dept['id'], // 部門唯一標識'children' => [], // 子節點(員工或子部門)// 保留元數據(可選,前端如需區分部門/員工可使用)'meta' => ['type' => 'department','id' => $dept['id']]];// 查詢部門下的員工(假設部門ID字段為department,需根據實際表結構調整)$staffList = Db::name('wecom_staff')->where('department', $dept['id']) // 員工表中部門關聯字段->field('id, name')->order('id ASC')->select(); // 轉換為數組// 轉換員工數據格式$deptData['children'] = array_map(function ($staff) {return ['text' => $staff['name'], // 員工顯示名稱'value' => 'staff_' . $staff['id'], // 員工唯一標識'isLeaf' => true, // 標記為葉子節點(無子節點)'meta' => ['type' => 'employee','id' => $staff['id']]];}, $staffList);$result[] = $deptData;}$this->success('獲取成功', $result);}
注意的點:tree->init()要傳三個參數,特別是第二第三個參數,第二個參數應該為父id的字段名,第三個是空格占位符,默認是 在html會正常識別,但是小程序不行,所以要自己定義占位符。
tree類文件的注釋也寫的非常 清晰了。
設置了自定義占位符和默認的區別。
前端頁面的調用,截取了部分:
<template><!-- 借用信息表單 --><view class="form-section"><view class="form-item"><text class="label">所屬部門</text><uni-data-picker :localdata="departmentData" popup-title="請選擇班級" @change="onchange"@nodeclick="onnodeclick"></uni-data-picker></view></view>
</template><script setup>import {ref,computed} from 'vue'import request from '@/utils/http2.js'const departmentData = ref([])onMounted(() => {// 加載部門樹request({url: '/api/wecomapi/getDepartmentAndStaff',method: 'GET'}).then(res=>{if (res.code) {departmentData.value = res.data;}})})</script>