How to display raw html with filter?
I have something like this:
K.json = function( json ) {
if( typeof json!=
For me, as @acdcjunior pointed out, this worked:
<p v-html="$options.filters.json(description)"></p>
Besides that, I had two filters to apply, and it also worked:
<p v-html="$options.filters.filter1($options.filters.filter2(description))"></p>
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, '>' ); // 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 '<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
<div id="app" class="container">
<h1>
v-html directive
</h1>
<div v-html="this.$options.filters.jsonFormatter(jsonData)"></div>
</div>
If you're just displaying the data then create a method:
json(jsonable) {
return jsonedValue;
}
then in the html
<div v-html="json(mydata)"></div>
For completeness, you have some options, like:
v-html="$options.filters.FILTERNAME(args)"
or:inner-html.prop="args | FILTERNAME"
orv-html="METHODNAME(args)"
, if you create a method.See demo below.
function json(text) {
// do your magic
return text.toUpperCase(); // just for demo
}
Vue.filter('json', function (value) {
return json(value);
})
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!'
},
methods: {
jsonMethod(v) {
return json(v); // create a "proxy" to the outer function
}
}
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
<p v-html="$options.filters.json(message)"></p>
<p :inner-html.prop="message | json"></p>
<p v-html="jsonMethod(message)"></p>
</div>