简体   繁体   English

在 v-html 属性中显示原始 html

[英]Display raw html in v-html attribute

I discover problem with rendering html from vue code.我发现从 vue 代码渲染 html 时出现问题。 I need to generate span from vue with raw html inside我需要从 vue 生成跨度,里面有原始的 html

<table>
    <tr>
        <td style="width:33%" v-html="diffText"></td>
    </tr>
</table>
this.diff.forEach((part) => {
    let color = part.added ? 'green' :
                    part.removed ? 'red' : 'grey';
    this.diffText += "<span style='color:" + color + "'>" + part.value + "</span>";
});

part.value is html raw. part.value是原始的 html。

<table>
  <tr>
    <td style="width:33%">
      <pre v-for="(d, key) in diff"
           :key="key"
           :style="{ color: getColor(d) }"
           v-html="d.value" />
    </td>
  </tr>
</table>
...
  methods: {
    getColor(d) {
      return d.added ? 'green' : d.removed ? 'red': 'grey' 
    }
  }
...

...will likely produce the result you're looking for. ...很可能会产生您正在寻找的结果。 Since the contents of a <pre> tag does not get intepreted as HTML, you can also use v-text instead of v-html here.由于<pre>标签的内容不会被解释为 HTML,因此您也可以在此处使用v-text而不是v-html

Note: Unlike <xmp> , <pre> tags are not obsolete and their implementation across browsers is consistent.注意:<xmp>不同, <pre>标签并没有过时,它们在浏览器中的实现是一致的。

I find out that best solution is to replace all "<" to "<" and ">" to ">"我发现最好的解决方案是将所有“<”替换为“<”,将“>”替换为“>”

You can use <xmp> tags.您可以使用<xmp>标签。

<xmp>
    <div> I am a Div</div>
</xmp>

this will render <div> I am a Div</div> .这将呈现<div> I am a Div</div>

More ways to do this:更多的方法来做到这一点:

1. Replace some special chars from your raw html string: 1. 替换原始 html 字符串中的一些特殊字符:

  • Replace the & character with &amp;&字符替换为&amp;
  • Replace the < character with &lt;<字符替换为&lt;
  • Replace the > character with &gt>字符替换为&gt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM