对于一些没什么固定结构的json,直接json.stringify展示出来不够美观,但又无法确定结构,展示很麻烦,于是打算写个组件来将其展示出来,由于项目中用了antd组件库,所以直接借用其中的tree来展示,这里主要是调整格式来适应antd组件
<template>
<div>
<a-tree :tree-data="treeData" :default-expand-all="true" />
</div>
</template>
<script>
export default {
computed: {
treeData() {
const result = this.expandObj('详情树', this.jsonData);
return [result];
}
},
props: {
jsonData: {
required: true,
type: Object,
default: () => {}
}
},
methods: {
getType(item) {
return Object.prototype.toString.apply(item).slice(8, -1);
},
expandObj(label, value) {
if (this.getType(value) === 'Object' || this.getType(value) === 'Array') {
// 对象,依次拓展
let result = [];
for (let key of Object.keys(value)) {
result.push(this.expandObj(key, value[key]));
}
return {
title: `${label}`,
children: result
};
} else {
// 若是普通类型,返回正常对象
return {
title: `${label}:${value}`,
isLeaf: true
};
}
}
}
};
</script>
使用时只需要挂上:json-data=xxxx就行了,效果如下