简体   繁体   中英

Display raw html in v-html attribute

I discover problem with rendering html from vue code. I need to generate span from vue with raw html inside

<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.

<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.

Note: Unlike <xmp> , <pre> tags are not obsolete and their implementation across browsers is consistent.

I find out that best solution is to replace all "<" to "<" and ">" to ">"

You can use <xmp> tags.

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

this will render <div> I am a Div</div> .

More ways to do this:

1. Replace some special chars from your raw html string:

  • Replace the & character with &amp;
  • Replace the < character with &lt;
  • Replace the > character with &gt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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