级联
数据格式转换
iview级联要求的数据格式
[{
value: 'beijing',
label: '北京',
children: [
{
value: 'tiantan',
label: '天坛'
}
]
}]
现有的数据格式
[{
code: 'beijing',
name: '北京',
list: [
{
code: 'tiantan',
name: '天坛',
list: []
}
]
}]
如果要使用iview的级联,就要把数据转换成上述要求的格式
递归处理
function convertTree (tree) {
const result = [];
tree.forEach((item) => {
// 解构赋值并重命名
let { code: value, name: label, list: children } = item;
// 如果有子节点,递归
if (children) {
children = convertTree(children);
}
result.push({ value, label, children });
})
return result
}
优化复用
// map
{
value: 'code',
label: 'name',
children: 'list'
}
function convertTree (tree, map) {
const result = [];
tree.forEach((item) => {
// 读取 map 的键值映射
let value = item[ map.value ];
let label = item[ map.label ];
let children = item[ map.children ];
// 如果有子节点,递归
if (children) {
children = convertTree(children, map);
}
result.push({ value, label, children });
})
return result
}
提取放在工具类中
utils->recursion.js
const recursion = {
convertTree: function (tree, map) {
const result = [];
tree.forEach((item) => {
// 读取 map 的键值映射
let value = item[ map.value ];
let label = item[ map.label ];
let children = item[ map.children ];
// 如果有子节点,递归
if (children) {
children = this.convertTree(children, map);
}
result.push({ value, label, children });
})
return result
},
}
export default recursion
树
utils->recursion.js
const recursion = {
convertTree: function (tree, map) {
const result = [];
tree.forEach((item) => {
// 读取 map 的键值映射
let expand = false;
let title = item[ map.title ];
let children = item[ map.children ];
// 如果有子节点,递归
if (children) {
children = this.convertTree(children, map);
}
result.push({ expand, title, children });
})
return result;
},
}
export default recursion
组件
import recursion from '@/utils/recursion'
const map = {
title: 'name',
children: 'list'
}
const resultArr = recursion.convertTree(res.data, map)