2017-08-07 113 views
1

我尝试过滤我的JSON字符串到JSON突出显示语法或有点像JSON美元pre元素标签。我不想要一个树json查看器,但只是一个不错的JSON语法高亮。美化json字符串vuejs2 webpack

模板

<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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;') 
     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链接

https://jsfiddle.net/Ljck1wmL/5/

+0

Vue实例的'data'应该**不是**函数。只有组件有这样的要求 – Phil

+0

@它有html标签。我包装了一些匹配正则表达式字符串与特殊类跨度标签。所以我可以设计它。 –

+0

您在JSFiddle中使用Vue v1。您在本地使用哪个版本的Vue和vue-loader? – Phil

回答

1

我有点找不到那个{{{ html }}}语法的任何文件。根据official documentation,您应该使用v-html指令。

此外,Vue 2.x过滤器仅在胡须和v-bind表达式中可用。 You cannot use a filter in v-html

对于其他任何情况,您应该使用计算属性或方法。

<pre v-html="prettyAreaData"></pre> 

computed: { 
    prettyAreaData: function() { 
    var value = this.areaData; 
    // and so on with the rest of your function 

我已经更新您的jsfiddle使用Vue的2.X,我假设你正在使用本地。我也修复了data函数是一个普通的对象。

https://jsfiddle.net/Ljck1wmL/7/

+0

我已经尝试过计算数据和函数,但css没有呈现。 –

+0

我不知道你的意思是*“css not rendered”*。你的意思是CSS中的样式没有被应用?如果是这样,你的CSS如何包含?如果它是一个独立的组件(例如'Hello.vue'),它应该在'