javascript
复制代码
//在 el-tree 中使用 render-content 插槽来展示文件大小
<template>
<div>
<el-tree
ref="tree"
v-loading="treeData.loading"
:data="treeData.data"
node-key="id"
:props="defaultProps"
:render-content="renderTreeNode">
</el-tree>
</div>
</template>
<script>
export default {
data() {
return {
treeData: {
loading: false,
data: [
{
id: 1,
name: '文件1',
fileSize: 391055,
fileCount: 1,
children: []
},
// 更多节点数据...
]
},
defaultProps: {
children: 'children',
label: 'name' // 这里假设节点的显示文本是 name 属性
}
};
},
methods: {
// 显示文件大小及数量
renderTreeNode (h, { node, data, store }) {
const fileSizeDisplay = this.safeFormatFileSize(data.fileSize);
const fileCountDisplay = data.fileCount || '0';
return h('span', [
h('span', data.name),
h('span', { style: { marginLeft: '2px', color: '#ccc' } }, `(${'大小'}:${fileSizeDisplay}, ${'数量'}:${fileCountDisplay})`)
]);
},
//确保 data.fileSize 存在且不是 null
safeFormatFileSize (val) {
const safeBytes = val ? val : 0;
return this.formatFileSize(safeBytes);
},
//转译字节变成文件大小
formatFileSize (bytes) {
if (bytes === 0) return '0B';
const sizes = ['B', 'KB', 'MB', 'GB'];
let i = 0;
while (bytes >= 1024 && i < sizes.length - 1) {
bytes /= 1024;
i++;
}
return `${bytes.toFixed(2)}${sizes[i]}`;
},
}
};
</script>
<style scoped>
</style>