数据:dataList: [‘10000’, ‘10000001’, ‘10000001001’, ‘20000’, ‘20000002’]
需要的效果:1. 8-3切割的效果
2. 5-3-3切割的效果
<template>
<div id="app">
<el-tree :data="treeData" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
// 动态规则,例如 "5-3-3"
rule: '8-3',
// 动态数据列表
dataList: ['10000', '10000001', '10000001001', '20000', '20000002'],
treeData: [], // 将会填充的树形结构数据
defaultProps: {
children: 'children',
label: 'label'
}
};
},
created() {
this.generateTree();
},
methods: {
generateTree() {
const segments = this.rule.split('-').map(Number);
const root = {};
this.dataList.forEach(id => {
let node = root;
let start = 0;
for (let i = 0; i < segments.length; i++) {
const end = start + segments[i];
const segment = id.slice(start, end);
if (!node[segment]) {
node[segment] = { label: segment, children: {} };
}
node = node[segment].children;
start = end;
}
});
function toTreeArray(node) {
return Object.keys(node).map(key => ({
...node[key],
children: toTreeArray(node[key].children)
})).filter(item => item.label !== '');
}
this.treeData = toTreeArray(root);
},
handleNodeClick(data) {
console.log('Node clicked:', data);
}
},
watch: {
// 监听规则或数据的变化以重新生成树
rule: 'generateTree',
dataList: 'generateTree'
}
};
</script>
<style>
/* 添加样式 */
</style>