Vue3 V Html
## Vue.js 3 `v-html` Directive
The `v-html` directive in Vue 3 is a built-in directive used to update an element's `innerHTML`. Unlike standard data binding (mustache syntax `{{ }}`), which renders data as plain text, `v-html` parses and renders the bound string as actual HTML.
---
## Technical Overview
* **Expected Value Type:** `string`
* **Primary Function:** Updates the element's `innerHTML`.
* **Rendering Behavior:** Parses HTML tags and renders them as live DOM elements.
---
## Basic Usage & Syntax
To use `v-html`, add the directive to an HTML element and bind it to a data property containing an HTML string.
```html
```
### Difference Between `v-html` and `v-text`
It is important to understand how `v-html` differs from `v-text` (or standard mustache interpolation):
| Directive | Rendering Type | Example Input | Rendered Output |
| :--- | :--- | :--- | :--- |
| **`v-text`** (or `{{ }}`) | Plain Text | `'Hello'` | `Hello` (Tags are escaped and visible) |
| **`v-html`** | Raw HTML | `'Hello'` | **Hello** (Rendered as bold text) |
---
## Practical Examples
### 1. Rendering Rich Text Content
A common use case for `v-html` is displaying rich text content fetched from a database, headless CMS, or external API.
#### Composition API (Recommended)
```vue
```
#### Options API
```vue
```
---
## Critical Security Warning: XSS Vulnerability
> β οΈ **Security Risk:** Dynamically rendering arbitrary HTML can easily lead to **Cross-Site Scripting (XSS)** vulnerabilities. If malicious scripts are injected into the HTML string, they will execute in the user's browser.
### Best Practices for Security:
1. **Never** use `v-html` on user-generated content (e.g., comments, forum posts, profile names) without sanitization.
2. **Only** render trusted content from your own secure database or trusted APIs.
3. **Sanitize HTML** if you must render user input. Use a dedicated sanitization library like (https://github.com/cure53/DOMPurify) before passing the string to `v-html`:
```javascript
import DOMPurify from 'dompurify'
// Sanitize the untrusted HTML string before rendering
const safeHTML = DOMPurify.sanitize(untrustedUserInput)
```
---
## Important Implementation Details
### 1. Component Scoped Styles Do Not Apply
In Vue, when using `
```
### 2. Single-File Component (SFC) Template Limitations
You cannot use `v-html` to resolve Vue component templates. If you try to pass a string containing Vue components (e.g., ` `) to `v-html`, the browser will treat them as unknown custom HTML elements and will not compile or mount them as Vue components.
YouTip