Vue3 v-html Directive
v-htmlThe directive is used to update the element's innerHTML, rendering the content as raw HTML.
Basic Description
v-htmlThe directive inserts the value of its bound expression into the element as HTML. This is very useful when rich text content needs to be rendered.
- Expected Type: string
- Function: Updates the element's innerHTML, which renders raw HTML.
Use Cases
1. Rendering Rich Text Content
When HTML content is obtained from the server and needs to be rendered:
Example
<template>
<div>
<h2>Article Content</h2>
<article v-html="articleContent"></article>
</div>
</template>
<script>
export default {
data() {
return {
articleContent: `
<h3>What is Vue.js</h3>
<p>Vue.js is a progressive JavaScript framework.</p>
`
}
}
}
</script>
<div>
<h2>Article Content</h2>
<article v-html="articleContent"></article>
</div>
</template>
<script>
export default {
data() {
return {
articleContent: `
<h3>What is Vue.js</h3>
<p>Vue.js is a progressive JavaScript framework.</p>
`
}
}
}
</script>
Security Warning
Security Issues: Dynamically rendering arbitrary HTML may cause XSS (Cross-Site Scripting) attacks. Always ensure that the content of v-html is trustworthy, and never use v-html on user-submitted content.
Difference from v-text
| Directive | Function | Example |
|---|---|---|
| v-text | Renders content as plain text | v-text="'test'" displays <b>test</b> |
| v-html | Parses content as HTML | v-html="'test'" displays test (bold) |
Other Extensions
Vue3 Built-in Directives