How to Use v-html in Vue: Syntax, Example, and Tips
Use the
v-html directive in Vue to insert raw HTML content into an element. Bind it to a data property containing HTML as a string, and Vue will render it inside the element instead of escaping it.Syntax
The v-html directive binds raw HTML content to an element. It replaces the element's inner content with the HTML string you provide.
v-html="htmlContent": Binds thehtmlContentdata property as raw HTML.- The bound value must be a string containing valid HTML.
- Vue will render the HTML inside the element instead of escaping it.
vue
<div v-html="htmlContent"></div>Example
This example shows how to use v-html to render a string containing HTML tags inside a Vue component.
vue
<template>
<div>
<h2>Rendered HTML Content:</h2>
<div v-html="htmlContent"></div>
</div>
</template>
<script setup>
import { ref } from 'vue'
const htmlContent = ref('<strong style="color: green;">Hello, Vue with v-html!</strong>')
</script>Output
Rendered HTML Content:
Hello, Vue with v-html! (in bold green text)
Common Pitfalls
Using v-html can cause security risks if you insert untrusted HTML, leading to cross-site scripting (XSS) attacks. Always sanitize any HTML from users before binding it.
Also, v-html replaces the element's inner content, so Vue directives or components inside that HTML won't work.
vue
<!-- Wrong: Binding untrusted user input directly --> <div v-html="userInput"></div> <!-- Right: Sanitize userInput before binding --> <div v-html="sanitizedUserInput"></div>
Quick Reference
- Use: To render raw HTML strings inside elements.
- Bind: A string containing HTML.
- Security: Sanitize HTML to avoid XSS.
- Limitations: Vue directives inside raw HTML won’t work.
Key Takeaways
Use
v-html to render raw HTML strings inside Vue elements.Always sanitize any HTML content from users before using
v-html to prevent security risks.v-html replaces the element’s inner content and does not compile Vue directives inside it.Bind
v-html to a string data property containing valid HTML markup.Avoid using
v-html for complex templates; prefer Vue components for dynamic content.