ElementUI tree的取值与回显
目的
场景一
选择树的节点后,希望提交当前选中的节点,以及节点对应的父级节点。 比如下面结构,当我选中字典管理时,我希望能够获取到的ids = [1,2,3]
{
"id": "1",
"label": "资源",
"type": "menu",
"children": [
{
"id": "2",
"label": "系统设置",
"type": "menu",
"children": [
{
"id": "3",
"label": "字典管理",
"type": "menu",
"children": []
},
{
"id": "4",
"label": "公共配置",
"type": "menu",
"children": []
}
]
}
]
}
场景二
回显处理:将上述数据回显时,默认情况会选中所有,因为elementui的树是根据父级的选中状态自动选中所有子节点。
解决方案
场景一
思路
- 提交时获得最底层的选中节点;
- 可以通过遍历子节点,分别获取父级节点标识;
- 需要利用递归。
相关代码
// 获取完全选中的节点
var treeKeys = this.$refs.tree2.getCheckedKeys()
// 最终选中的包括半选中的节点数组
var ids = []
// 调用获取所有节点的方法
this.getTreeNodes(treeKeys, ids)
// distinct 是自定义的数组去重方法
ids = this.distinct(ids)
var result = ''
if (ids && ids.length > 0) {
result = ids.join(',')
}
// 逗号隔开的字符串
console.debug(result)
核心代码如下
// 获取选中的树节点
getTreeNodes (childNodes, ids) {
// 将所有选中的子节点保存
for (var i = 0; i < childNodes.length; i++) {
ids.push(childNodes[i])
// 获取父级节点
this.getTreeParentNode(childNodes[i], ids)
}
},
// 递归查询所有上级数据
getTreeParentNode (id, ids) {
// 获取当前节点的上级节点id
var parentId = this.$refs.tree2.getNode(id).parent.data.id
if (parentId && parentId !== null) {
ids.push(parentId)
this.getTreeParentNode(parentId, ids)
}
}
公共方法(去重)
export default {
install (Vue, options) {
/** js数组去重 @author GaoYuan */
Vue.prototype.distinct = (arr) => {
var res = []
var json = {}
for (var i = 0; i < arr.length; i++) {
if (!json[arr[i]]) {
res.push(arr[i])
json[arr[i]] = 1
}
}
return res
}
}
}
场景一
思路
- 利用树的属性 check-strictly
相关代码
// 获取权限树
getTree () {
this.treeLoading = true
/** 将树的父级与子级关联移除 */
this.checkStrictly = true
// 开始请求接口
this.$axios({
method: 'get',
url: '/sys/resource/listTree',
params: {}
})
.then(res => {
this.treeLoading = false
this.$log('查询结果', res)
this.allResource = res
/** 将树的父级与子级关联绑定 */
this.checkStrictly = false
})
.catch(err => {
this.treeLoading = false
this.$log('错误信息', err)
})
}
主要代码是
/** 将树的父级与子级关联移除 */
this.checkStrictly = true
/** 将树的父级与子级关联绑定 */
this.checkStrictly = false
博客
https://my.oschina.net/gmarshal/blog/1843526
欢迎关注我的个人微信订阅号:(据说这个头像程序猿专用)