
VUE将代码json格式展示到界面
有一个需求后端把系统日志传给前端,传出得格式为没有空格换行得字符串格式代码,需要全端格式化展示在界面。
·
有一个需求后端把系统日志传给前端,传出得格式为没有空格换行得字符串格式代码,需要全端格式化展示在界面。
首先我们需要拿到后端数据进行格式化。把数据传入到syntaxHighlight()函数中。
syntaxHighlight(json){
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2);
}
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function(match) {
var 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>';
});
}
调用syntaxHighlight函数把数据赋值给codedatatwo。
this.codedatatwo = this.syntaxHighlight(datatwo //把数据传值给函数进行格式化解析)
在界面中使用pre 标签进行进一步得格式化。并使用html 标签把数据添加。
<el-card class="card">
<pre v-html="codedatatwo"></pre>
</el-card>
更多推荐
所有评论(0)