VueJS2 v-html with filter

前端 未结 4 403
天命终不由人
天命终不由人 2021-02-04 04:53

How to display raw html with filter?

I have something like this:

K.json = function( json ) {
    if( typeof json!=         


        
4条回答
  •  别跟我提以往
    2021-02-04 05:07

    The issue is that your HTML is processed before the filter is added to your Vue instance. Try like this: JSFiddle

    var jsonFormatter = function(json){
        if( typeof json!='string' ) json = JSON.stringify( json, null, 2 );
        json = json.replace( //g, '>' ); // replace(/&/g, '&')
        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 '' + match + '' + 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

    v-html directive

提交回复
热议问题