Vue v-html Directive

Welcome to The Coding College, where we make coding concepts easy and approachable! In this article, we’ll dive into the v-html directive in Vue.js, which allows you to render raw HTML content dynamically.

We’ll explore its syntax, use cases, potential risks, and best practices to ensure your applications remain secure and efficient.

What is the v-html Directive?

The v-html directive is used in Vue.js to insert raw HTML content into the DOM. Unlike standard text binding (e.g., {{ text }}), which escapes HTML for safety, v-html directly renders the provided HTML string.

Syntax

Here’s the basic syntax for using v-html:

<element v-html="htmlContent"></element>
  • htmlContent: A string containing valid HTML that you want to render.

Example: Rendering Raw HTML

Without v-html

<template>
  <div>
    {{ htmlContent }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      htmlContent: '<strong>Bold Text</strong>'
    };
  }
};
</script>

Output:

<strong>Bold Text</strong> is displayed as plain text, not bolded.

With v-html

<template>
  <div v-html="htmlContent"></div>
</template>

<script>
export default {
  data() {
    return {
      htmlContent: '<strong>Bold Text</strong>'
    };
  }
};
</script>

Output:

Bold Text (rendered as bolded text in the DOM).

Use Cases

1. Rendering HTML from a Database

When building a blog or CMS, v-html can render rich content fetched from a database.

<template>
  <article v-html="postContent"></article>
</template>

<script>
export default {
  data() {
    return {
      postContent: '<h1>Welcome to Vue.js</h1><p>This is a paragraph.</p>'
    };
  }
};
</script>

2. Dynamic Content Injection

You can use v-html to inject dynamic HTML, such as tooltips, modals, or custom messages.

3. Replacing Markdown with HTML

Convert markdown to HTML using a parser, then bind the HTML to your component.

Security Risks

The v-html directive comes with potential risks if the HTML content is not sanitized.

Risk: Cross-Site Scripting (XSS)

If the HTML content includes malicious scripts, these will execute in the browser.

Example of Vulnerable Code:

<template>
  <div v-html="userInput"></div>
</template>

<script>
export default {
  data() {
    return {
      userInput: '<script>alert("Hacked!");</script>'
    };
  }
};
</script>

Output:

The script will execute, displaying an alert box with the message “Hacked!”.

Preventing XSS

  1. Sanitize User Input
    Use a library like DOMPurify to clean the HTML before rendering it.

Example with DOMPurify:

<template>
  <div v-html="safeHtml"></div>
</template>

<script>
import DOMPurify from 'dompurify';

export default {
  data() {
    return {
      rawHtml: '<script>alert("Hacked!");</script><p>Safe content</p>'
    };
  },
  computed: {
    safeHtml() {
      return DOMPurify.sanitize(this.rawHtml);
    }
  }
};
</script>

Output:

Only the safe <p>Safe content</p> is rendered.

  1. Trust Only Safe Sources
    Ensure the content comes from trusted sources, like your own database or API.
  2. Avoid User-Generated HTML
    Do not use v-html to display untrusted content.

Best Practices

  1. Use v-html Sparingly
    Render raw HTML only when absolutely necessary.
  2. Prefer Template Syntax
    For most cases, standard Vue bindings ({{ }} or v-bind) are safer and easier to manage.
  3. Always Sanitize
    Clean any HTML input using a library like DOMPurify to avoid XSS vulnerabilities.
  4. Test Thoroughly
    Regularly test your application for security vulnerabilities, especially when handling dynamic content.

Comparison: v-html vs Interpolation

FeatureInterpolation ({{ }})v-html
Escapes HTMLYesNo
Displays Raw HTMLNoYes
Security RiskLowHigh (if unsanitized)
Recommended UsageGeneral useSpecific cases only

Conclusion

The v-html directive is a powerful feature in Vue.js for rendering raw HTML dynamically. However, it should be used with caution due to the inherent security risks. Always sanitize content and prefer safer alternatives wherever possible.

For more Vue tutorials and coding resources, visit The Coding College.

Leave a Comment