在Vue2中,您可以通过将值包装在
<div v-html="computedValue"/>
Run Code Online (Sandbox Code Playgroud)
但是,无论是否需要,都会在每个元素周围添加一个额外的<div>标签。我想做的是选择性地将值视为原始HTML,如果它是非HTML文本,则不需要额外的div标签。
我现在想到的唯一方法是添加两个额外的计算属性,并多次计算该值:
<div v-if="containsHtml" v-html="computedValue"/>{{nonHtmlValue}}
Run Code Online (Sandbox Code Playgroud)
组件
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];
}
}
})
Run Code Online (Sandbox Code Playgroud)