In Vue2, you can treat a value as HTML by wrapping it in a
<div v-html="computedValue"/>
However that adds an extra <div> tag around every element, whether or not it is required. What I'd like to do is optionally treat a value as raw HTML without requiring the extra div tag if it is non-html text.
The only way I can think of doing it right now requires adding 2 additional computed properties, and calculating the value multiple times:
<div v-if="containsHtml" v-html="computedValue"/>{{nonHtmlValue}}
The component
Vue.component("datatable-cell", {
template: `
<td>{{computedValue}}</td>
<!-- above is ideal I'm trying to avoid
<td><div v-if="containsHtml" v-html="computedValue"/>{{nonHtmlValue}}</td>
-->
`,
props: ["row","column"],
computed: {
containsHtml: function(){
return this.computedValue != null && this.computedValue.charAt[0] == "<";
},
nonHtmlValue: function(){
if(this.containsHtml) return "";
return this.computedValue;
},
computedValue: function(){
if(this.column.template){
var templateValue = this.column.template(this.row);
if(isSafeMarkup(templateValue)){
//Treat as HTML - how????
return templateValue;
}else{
//Escape and treat as text. This already works
return templateValue;
}
}else{
return this.row[column.name];
}
}
})