本人使用的是vue2工程,近期有一个功能,在前端编辑json配置文件,要求将json关键字进行高亮,以增加其可读性,请问有组件可以实现吗,举例,以下是idea高亮json的效果。
<template>
<div>
<p>vue-json-editor</p>
<vue-json-editor v-model="json" :show-btns="true" :expandedOnStart="true" mode="code"
@json-change="onJsonChange"></vue-json-editor>
</div>
</template>
<script>
import vueJsonEditor from 'vue-json-editor'
export default {
data() {
return {
json: {
msg: 'demo of jsoneditor'
}
}
},
components: {
vueJsonEditor
},
methods: {
onJsonChange(value) {
console.log('value:', value)
}
}
}
</script>
<style>
.ace_variable {
color: red !important;
}
</style>
这块插件应该挺多的 Jsbeautifier JS代码美化库。你试下看看效果
看看这段代码
/**
* 搜索出的列表中文字的颜色高亮
* @param prope 需要高亮的属性
*/
highLightText = (prope) => {
// searchval是搜索的关键字,list是原始的数据
const {searchval,list} = this.state
// 最终输出的数据
let matchVal = [];
list.forEach((item, index) => {
let isMatch = true, // 是否匹配
rawVal = item[prope] // 进行匹配的原始字符串
matchVal[index] = [] // 初始化数据
while (isMatch) {
// 对关键字的位置进行匹配
let pos = rawVal.indexOf(searchval)
if (pos === -1) { // 没有匹配到关键字
isMatch = false
matchVal[index].push({ [prope]: rawVal.substring(0, rawVal.length),name: item.name })
} else {
// 当前匹配的位置+关键字的长度
let matchEnd = pos + searchval.length
// 没有匹配到的关键字
matchVal[index].push({ [prope]: rawVal.substring(0, pos),name: item.name })
// 匹配到的关键字
matchVal[index].push({ [prope]: rawVal.substring(pos, matchEnd), matched: true,name: item.name })
// 将匹配到的文字进行删除,将原始数据进行重新筛选
rawVal = rawVal.substring(matchEnd, rawVal.length)
// 当匹配的长度到了末尾,将不再进行匹配
if (!rawVal && rawVal.length < 1) {
isMatch = false
}
}
}
})
return matchVal
}
json在html页面上高亮显示
js
function syntaxHighlight( json )
{
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 )
{
console.log(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>';
} );
}
var data={
"a":1,
"b":2
}
var str = JSON.stringify( data, undefined, 4 );
$("#detail").html( syntaxHighlight( str ));
html
<pre id="detail" class="form-control" style="width:800px;height:400px;max-width:800px;max-height:500px"></pre>