传值
首先要做的就是将树渲染出来,并且能够取到对应的值
utils-recursion.js
const recursion = {
// 转换树结构并将需要的值存进树中
// 存值为:除了树结构必须的值外,我需要发送给后台的值 (code)
convertTree: function (tree, map) {
const result = [];
tree.forEach((item) => {
// 读取 map 的键值映射
let expand = true;
let checked = false;
let title = item[ map.title ];
let code = item[ map.code ];
let children = item[ map.children ];
// 如果有子节点,递归
if (children) {
children = this.convertTree(children, map);
}
result.push({ expand, checked, code, title, children });
})
return result;
},
}
export default recursion
转换过程
import recursion from '@/utils/recursion'
// 后台返回的字段
const map = {
title: 'name',
children: 'finClassList',
code: 'code'
}
this.typeTree = recursion.convertTree(res.data, map)
获取选中的树的值
<Tree :data="typeTree" @on-check-change="getTypeTree" show-checkbox></Tree>
getTypeTree (arr) {
this.typeTreeResult = []
arr.forEach((item) => {
// 如果全选,会将子级和父级全部返回,若只需子级,则将父级去除
if (item.title !== '父级名称' ) {
this.typeTreeResult.push(item.code)
}
})
}
全选
utils-recursion.js
const recursion = {
// 转换树结构并将需要的值存进树中
convertTree: function (tree, map) {
// ...
},
// 设置全选与反选树,第一个参数值为树,第二个参数值为true为全选,false为反选
convertTreeCheck: function (tree, checkVal) {
const result = [];
tree.forEach((item) => {
// 读取 map 的键值映射
let expand = true;
let checked = checkVal;
let title = item.title;
let code = item.code;
let children = item.children;
// 如果有子节点,递归
if (children) {
children = this.convertTreeCheck(children, checkVal);
}
result.push({ expand, code, checked, title, children });
})
return result;
},
}
export default recursion
全选
this.typeTree = recursion.convertTreeCheck(this.typeTree, true)
反选
this.typeTree = recursion.convertTreeCheck(this.typeTree, false)
回显
因为设计方式,选中的树会在树的上方逐个列出来,所以这里对回显的处理是不在树中不显示已选的节点,即在向后台请求数据前,将已选的数据发送给后台,将这些数据过滤掉。
如果要回显的话,其实和上面的代码没什么区别,将返回的数据设置是否选中即可。
utils-recursion.js
const recursion = {
// 转换树结构并将需要的值存进树中
convertTree: function (tree, map) {
// ...
},
// 设置全选与反选树,第一个参数值为树,第二个参数值为true为全选,false为反选
convertTreeCheck: function (tree, checkVal) {
// ...
},
// 回显树
convertTreeShow: function (tree, map) {
const result = [];
tree.forEach((item) => {
// 读取 map 的键值映射
let expand = true;
let checked = item[ map.checked ];
let title = item[ map.title ];
let code = item[ map.code ];
let children = item[ map.children ];
// 如果有子节点,递归
if (children) {
children = this.convertTreeShow(children, map);
}
result.push({ expand, code, checked, title, children });
})
return result;
}
}
export default recursion
回显树
const map = {
title: 'name',
children: 'finClassList',
checked: 'flag',
code: 'code'
}
this.typeTree = recursion.convertTreeShow(tempTree, map)