需求描述:点击按钮弹出弹窗,数据量较大,所以为懒加载树形控件(可搜索)
1. 节点只可进行单选
2. 添加和编辑共用一个弹窗(编辑页面进入弹窗:选中节点后点取消回到编辑页面,再次进入编辑默认选中的应该是上一次点击确定后的节点)
lazy 控制懒加载;node-key 树节点用来作为唯一标识的属性(做单选必须要用)
具体实现:
<el-tree
ref="departTree"
:props="props"
:load="loadNode"
node-key="id"
lazy
show-checkbox
check-strictly
:filter-node-method="filterNode"
:default-checked-keys="checkedKey"
:default-expanded-keys="expandKey"
@check="checkJoint"
></el-tree>
checkedKey、expandKey分别是默认选中节点和默认展开节点(都是数组)
注意:如果测试中使用的不是用变量进行props传参,那需要手动清除该值,否则会出现再次打开页面编辑会显示两个默认选中节点。一个是写死的默认节点值,一个是组件提供的
该数据可以和后端沟通,让后端处理好返回给你。否则就要通过默认节点来遍历查询需要展开的节点(数据量大,渲染效率低)
// 假数据
list: [
{
id: 0,
label: '江苏省',
children: [
{
id: 11,
label: '省本级',
children: [
{
id: 12,
label: '1'
},
{
id: 13,
label: '2'
},
{
id: 14,
label: '3'
}
]
},
{
id: 21,
label: '南京市',
children: [
{
id: 22,
label: '南京市市本级',
children: [
{
id: 221,
label: '1'
},
{
id: 222,
label: '2'
}
]
},
{
id: 23,
label: '南京市建邺区'
},
{
id: 24,
label: '南京市鼓楼区'
}
]
}
]
}
],
实现单选:
(element UI 中树型控件提供方法不唯一,只要能实现设置选中节点即可)
checkJoint (data) {
this.$refs.departTree.setCheckedNodes([data])
this.selectData = data //有需要可以记录选中节点的数据
},
实现编辑页面选中节点后点击取消,再次进入默认选中节点为上一次点击确定节点:
// 取消
cancel () {
// 将默认选中节点设为上一次点击确定选中的节点
this.$refs.departTree.setCheckedKeys(this.checkedKey)
this.$emit('input', false) //关闭弹窗
}
实现懒加载:
(懒加载具体实现和提供的数据是相关联的,请注意数据格式)
// 我造的数据是将结果一次性都给你了,如果格式不同,需要修改
loadNode (node, resolve) {
if (node.level === 0) {
return resolve([this.list[0]] || [])
}
// 其余节点处理
if (node.level >= 1) {
return resolve(node.data.children || [])
}
},