el-tree数据渲染超出省略
问题
<el-tree
:data="deptOptions"
:props="defaultProps"
:expand-on-click-node="false"
:filter-node-method="filterNode"
ref="tree"
default-expand-all
highlight-current
@node-click="handleNodeClick"
/>
- 如题,deptOptions是一个树结构,里面结点的值都是字符串,我希望将根节点的字符串长度限制在13个字符,后面超出直接加上’…’
- 通过直接给el-tree设置超出省略并没有解决问题,通过排查发现el-tree-node__label文字内容太多导致超出长度不显示省略号
解决
- 通过样式方案解决
<div class="head-container">
<el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
:filter-node-method="filterNode" ref="tree" default-expand-all highlight-current
@node-click="handleNodeClick">
<template v-slot="{node}">
<span :title="node.label" class="node-label">{{node.label}}</span>
</template>
</el-tree>
</div>
.node-label {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
- 通过数据处理方案解决
function formatDeptOptions(deptOptions, maxLength = 13) {
for (let i = 0; i < deptOptions.length; i++) {
const node = deptOptions[i];
if (node.label.length > maxLength) {
node.label = node.label.slice(0, maxLength) + '...';
}
if (node.children && node.children.length > 0) {
formatDeptOptions(node.children, maxLength);
}
}
}
// 假设deptOptions已经存在并初始化完毕
formatDeptOptions(deptOptions);
console.log(deptOptions);
- 效果