Table of contents
1. Background
- Technology: Vue3 + Element Plus
- Requirement: When selecting an organization, it will be displayed in a drop-down tree structure.
- Components used:
TreeSelect
tree selection component (el-tree-select
)
Official website document address:
- https://element-plus.gitee.io/zh-CN/component/tree-select.html
- https://element-plus.gitee.io/zh-CN/component/tree.html
A brief description:
el-tree-select
Components are a combination of el-tree
and el-select
, and their original properties have not been changed, so specific properties and methods still refer to el-tree
andel-select
Two, use
1. dom
<el-tree-select
v-model="form.deptId"
lazy
ref="treeRef"
:load="loadNode"
:props="{ value: 'deptId', label: 'deptName'}"
value-key="deptId"
node-key="deptId"
placeholder="请选择"
show-checkbox
check-strictly
highlight-current
:default-expanded-keys="defaultExpandedNodes"
/>
Related property description:
v-model id值。只要这个id值在树里能匹配上,就能够顺利回显出其label值。
lazy 开启懒加载
load 加载子树数据的方法
value-key 作为 value 唯一标识的键名。简单说就是主键,根据自己后端返回的字段修改
node-key 每个树节点用来作为唯一标识的属性。简单理解为树节点的主键,同value-key
props 配置选项。一般配置value和label的属性值
show-checkbox 开启复选框
check-strictly 可选择任一级别
highlight-current 选中高亮显示
default-expanded-keys 默认展开节点的key数组(懒加载时用于数据回显,这个属性非常关键)
2.methods
/** 懒加载获取树形结构*/
function loadNode(node, resolve) {
// node其实是需要展开树节点,但是第一次的node是个无用的数据,可以认为这个node是element给我们创建的,判断的话,就是level等于0
if (node && node.level == 0) {
getDeptData(0, resolve);
} else {
getDeptData(node, resolve);
}
}
// 从后端获取数据列表
function getDeptData(node, resolve){
//构造参数
let params = {
};
params.pageSize = 100;
if(node == 0){
//根节点
params.deptId = '1';
}else if(node.data.deptId){
//中间节点
params.parentId = node.data.deptId;
}else{
return resolve([]);
}
// listDept是像后端访问组织结构数据的接口,根据实际场景修改
listDept(params).then(response => {
let data = response.data;
return resolve(data);
})
}
The data structure returned by the backend
3. Return
Due to the use of lazy loading, unlike loading all the data at once, there is currently only ID, and the tree structure has not been rendered, which will result in no label echo. So we need to construct the tree nodes we want when the component is just rendered.
The attribute is used default-expanded-keys
, indicating the key array of the default expanded node. el-tree-select will automatically call the loadNode method according to the keys array, get the data and render the tree nodes.
default-expanded-keys
There are two ways of thinking about the value of :
- When adding/modifying, get the key path from the top-level root node to the currently selected node, such as: ['01','0101','010101'], and save it in the data table.
- Add such a field in the dept data table, the key path from the root node to the current node
Finally, while obtaining the content of the current data form, just assign the keys path of the node to be expanded to default-expanded-keys
, and it will be expanded to the current node by default and the label will be successfully echoed.