后端返回的列表数据中,有一列为json格式的对象字符串,el-column默认的鼠标悬停展示出的内容没有格式化展示,为字符串展示,看起来不美观,文章主要实现json的格式化展示
<el-table-column sortable prop="assetDetails" label="资产详情">
<template slot-scope="scope">
<el-tooltip class="item" effect="light" placement="top">
<div v-html="transAssetDetails(scope.row.assetDetails)" slot="content" style="max-width:500px"></div>
<div class="line">{{scope.row.assetDetails}}</div>
</el-tooltip>
</template>
</el-table-column>
//美化json字符串输出,可根据自己的需求调整修改
transAssetDetails(json) {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2);
}
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replaceAll('{','{<br>').replaceAll('}','<br>}').replaceAll(',',',<br>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
let cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
<style scoped>
.line {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.string {
color: green;
}
.number {
color: darkorange;
}
.boolean {
color: blue;
}
.null {
color: magenta;
}
.key {
color: red;
}
</style>
最终效果: