v-html

by bsschwa

HTML

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="https://rawgithub.com/yyx990803/vue/master/dist/vue.min.js"></script>
<div id="app" class="container">
     <h1>
        v-html directive
    </h1>
    <div v-html="this.$options.filters.jsonFormatter(jsonData)"></div>
</div>

JavaScript

var jsonFormatter = function(json){
    if( typeof json!='string' ) json = JSON.stringify( json, null, 2 );
    json = json.replace( /</g, '&lt;' ).replace( />/g, '&gt;' ); // replace(/&/g, '&amp;')
    var pattern = /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g;
    var html = json.replace( pattern, function( match ) {
        var cls = 'number';
        var suffix = '';
        if( /^"/.test( match ) ) {
            if( /:$/.test( match ) ) {
                cls = 'key';
                match = match.slice( 0, -1 );
                suffix = ':'
            } else {
                cls = 'string';
            }
        } else if( /true|false/.test( match ) ) {
            cls = 'boolean';
        } else if( /null/.test( match ) ) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>' + suffix;
    } );
    return html;
}

new Vue({
    el: '#app',
    data(){
        return {
        	jsonData: {dog: 'woof', nestedObject: {cat: 'meow'}}
        }
    },
    filters: {
    	jsonFormatter: jsonFormatter
    }
});
//Vue.filter( 'jsonFormatter', jsonFormatter ); // Doesn't work becuase happens after html is processed