【发布时间】:2018-01-14 08:04:16
【问题描述】:
我尝试将我的 json 字符串过滤成 JSON 高亮语法或有点像带有前置元素标签的 json 美化。我不想要一个树 json 查看器,只想要一个漂亮的 JSON 语法高亮。
模板
<div id="app">
<pre>{{{ json | jsonPretty }}}</pre>
</div>
vue
var vm = new Vue({
el: '#app',
data() {
return {
json:'{ "name: "John Doe" }'
}
},
filters: {
jsonPretty: function(value) {
let json = JSON.stringify(JSON.parse(value), null, 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>'
})
}
}
});
CSS
pre {
outline: 1px solid #ccc;
padding: 15px;
margin: 5px;
background: white;
}
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }
我尝试使用 jsfiddle,它正在工作,但是当我尝试使用 webpack 官方 vuejs 模板时,它显示错误
ERROR in ./~/vue-loader/lib/template-compiler?{"id":"data-v-4b8ecaca","hasScoped":true,"transformToRequire":{"video":"src","source":"src","img":"src","image":"xlink:href"}}!./~/vue-loader/lib/selector.js?type=template&index=0!./src/components/Hello.vue
(Emitted value instead of an instance of Error)
Error compiling template:
<div class="hello">
<div class="">
<pre>{{{ json | jsonPretty }}}</pre>
</div>
</div>
- invalid expression: {{{ json | jsonPretty }}}
@ ./src/components/Hello.vue 10:2-300
@ ./~/babel-loader/lib!./~/vue-loader/lib/selector.js?type=script&index=0!./src/App.vue
@ ./src/App.vue
@ ./src/main.js
@ multi ./build/dev-client ./src/main.js
编辑:添加 jsfiddle 链接
【问题讨论】:
-
Vue 实例的
data应该不是一个函数。只有组件有这个要求 -
@Phil 它有 html 标签。我用特殊的类跨度标签包装了一些匹配的正则表达式字符串。所以我可以设计它。
-
您在 JSFiddle 中使用 Vue v1。你在本地使用的是哪个版本的 Vue 和 vue-loader?
-
@Phil 我用户 vue 2 和 vue-loader ^12。我尝试用计算数据更改我的过滤器。它用特定的类解析 span 标签。但它不呈现风格。它与 vuejs 生命周期有关?
标签: javascript json webpack vuejs2