How to Render HTML in Vue.js

Published on August 27, 2020 30 sec read

Hello artisan, in this guide, we are going to render HTML as DOM element in Vue.js.

Table of Contents

Render HTML

We know that the innerHTML property sets or returns the HTML content (inner HTML) of an element. Vue has a built-in v-html directive to do the same thing.

Have a look at an exmaple:

App.vue
<template>
  <div v-html="htmlContent"></div>
</template>

<script>
export default {
  data() {
    return {
      htmlContent: "<p style='color:green'>Welcome to MNP.</p>",
    };
  }
};
</script>

Important Notes

We should sanitize HTML code before rendering to v-html directive. Otherwise, hackers will able to do cross-site scripting (XSS) attacks.

If we try to bind HTML like {{htmlContent}}, Vue will display the code without rendering.

That’s it. Thanks for reading. ­čÖé

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *