Skip to main content
  1. Tutorials/

Render Raw HTML In Your Vue Apps

Tutorials Vue.js

Though it’s not that often, sometimes there is actually a good reason for needing to insert raw HTML stored as strings into the DOM. Very rarely, of course. In most cases you should never do this, as this opens you up to a variety of XSS attacks. A somewhat valid use-case might be if you’re writing a new front-end component for an ancient legacy system that (shudders) stores HTML mixed with data in an aging database in the long-forgotten server room in some leased facility upstate. In that case, you might have to resort to rendering raw HTML in your app.
So let’s get started. First things first, break out your RegEx skills …
Just kidding. I’d rather not risk the fate of the known universe just to accommodate a legacy system.
Anyway, it turns out that Vue provides us with a nice little directive that can handle all this for us. Predictably, it’s called v-html.
To use it, pass a reference to a HTML string in your data model to v-html in your component template, like so:

  <div v-html="legacySystemHTML">

export default {
  data() {
    return {
      // Just like JSX! Oh wait...
      legacySystemHTML: `
        <FONT color="#faddad" size="-2">
          <MARQUEE>Please enter your name to continue.</MARQUEE>

And just like that, your HTML will be rendered into the component. If you update the legacySystemHTML property, the HTML will update accordingly.
Not bad!

Also, here’s a little somewhat-related secret. You can use the v-text property the same way, except it only sets the text content of an element.

No idea why you’d use that when you could just use Mustache expressions ({{ componentInnerText }}) instead, but it’s there!