实现目标
需要实现标题层级显示,如下图,也就是标题层级的el-tree展示。
数据结构转换目标
需要先将上述的数据结构调整成上面的数据结构。
数据结构转换过程
起初想要再加一层children来实现,但是,有出现可折叠的断层,所以还是采取了给text中前面加空格的方式来进行实现效果。
export function tranListToTreeData(x) {
x.forEach((value, index) => {
for (var a = index ; a < x.length; a++) {
if (x[index].level < x[a].level) {
x[a].Parentid = x[index].id
}
}
});
var c = arrayToTree(x, {
customID: "id",
parentProperty: "Parentid"
});
return c;
}
通过上面的代码进行实现数据结构的转换,level大小进行层级区分。
数据结构修改了之后,就是对跨层级的数据的text前加入适当的空格,进行格式的统一处理
function addIndentation(data) {
data.forEach((item) => {
if (item.children && item.children.length > 0) {
item.children.forEach((child) => {
const levelDifference = child.level - item.level - 1;
const indentation = '/u00A0/u00A0/u00A0/u00A0'.repeat(levelDifference);
child.text = indentation + child.text;
if (child.children && child.children.length > 0) {
addIndentation(child.children);
}
});
}
});
}
空格样式显示调整
将上述的数据再次进行处理之后,页面中样式依旧没有生效,文本前的空格会隐藏,文本中的多个空格会只显示一个,现在需要进行样式的修改调整。
<template>
<el-tree :data="data">
<span slot-scope="{ node }" style="white-space: pre-wrap;">
{{ node.text }}
</span>
</el-tree>
</template>
将对应的el-tree上加入了white-space:pre-wrap的样式,以实现空格的显示。