目标:
员工的部门信息是从树形部门信息中选择
思路:
发请求获取数据
对数据进行格式转换(数组转树)
绑定到el-tree
第一步:获取部门数据并进行树形处理
// 引入api方法
import { getDepartments } from '@/api/departments'
// 引入树形结构转换方法
import { tranListToTreeData } from '@/utils'
data() {
return {
treeData: [], // 定义数组接收树形数据
// 省略其它......
}
}
created() {
this.loadDepartments()
},
methods: {
// 省略
async loadDepartments() {
const res = await getDepartments()
console.log(res)
res.data.depts.shift() // 去掉第一个元素(公司名)
this.treeData = tranListToTreeData(res.data.depts)
},
}
第二步:使用 el-tree 展示数据
el-tree组件的位置:在el-input的下面
注意:element官网el-tree组件的写法是这样
但是数据基本是符合tree要求,所以只需要把label转成name就行
<el-form-item label="部门" prop="departmentName">
<el-input v-model="formData.departmentName" style="width:50%" placeholder="请选择部门"/>
<div class="tree-box">
+ <el-tree :data="treeData" :props="{ label: 'name' }" />
</div>
</el-form-item>
:props="{ label: 'name' }" 设置以哪个字段为准来显示节点
第三步:部门数据渲染
思考:
如果一个用户打开了这弹层,在没有选择部门的情况下,又关闭了这个弹层,那我们还需要去加载部门数据吗?
优化:
只有当用户在input框上点击了,我们把数据的获取改写成聚焦时再获取数据并渲染显示
在el-input上补充@foucs,回调中获取部门信息
<el-form-item label="部门" prop="departmentName">
<el-input
v-model="formData.departmentName"
style="width:50%"
placeholder="请选择部门"
+ @focus="hFocus"
/>
<div v-if="showTree" class="tree-box">
<el-tree :data="treeData" :props="{ label: 'name' }"/>
</div>
</el-form-item>
data(){
return {
showTree:false
}
},
methods:{
// 部门输入框,获取焦点
hFocus() {
// 发请求
this.loadDepartments()
},
async loadDepartments() {
try {
const res = await getDepartments()
console.log('getDepartments', res)
// shift会取出数组第一个元素,同时会改变源数组
res.data.depts.shift() // 删除第一个值
this.departments = tranListToTreeData(res.data.depts)// 保存数据
// 显示tree
this.showTree = true
} catch (err) {
console.log('getDepartmens', err)
}
},
}
第四步:赋值表单数据
点选部门时,将选中的部门信息展示到部门输入框中
思路:
给el-tree添加点击事件
只有叶子节点(没有下级的节点)才能被选上
element官网中node-click 事件
<el-tree
v-if="showTree"
:data="treeData"
:props="{ label: 'name' }"
@node-click="hNodeClick"
/>
添加事件处理
如果还有子节点就不做处理
把选中的内容显示在表单元素上
隐藏树
// 用户在部门结构树上点击
hNodeClick(data, node) {
console.log('用户在部门结构树上点击', data, node)
// 如果当前部门还有子部门,则不能选中
if (data.children.length) {
return
}
console.log('选中的是', data.name)
// 1. 把当前选中的显示在input框中
this.formData.departmentName = data.name
// 2. 隐藏tree
this.showTree = false
}