Directives are special instructions placed directly inside your HTML tags.
In Vue, all directives start with the v- prefix so you can easily identify them.
They tell Vue to do something specific with that DOM element, like hiding it or changing its text.
Before diving into v- directives, let's look at the most common way to display data.
Text interpolation uses double curly braces {{ }}, often called the "Mustache" syntax.
Vue replaces the mustache tag with the value of the corresponding property from your data object.
<div id="app">
<p>Message: {{ textMessage }}</p>
</div>
The v-text directive does the exact same thing as the mustache syntax.
It updates the element's text content by completely overwriting whatever is inside it.
However, using double curly braces is generally preferred because it is much more readable.
<!-- These two lines achieve the exact same result -->
<p>{{ textMessage }}</p>
<p v-text="textMessage"></p>
Sometimes, your data might contain actual HTML markup (like <strong> or <em> tags).
If you use double curly braces, Vue will output it as plain, escaped text for security reasons.
To force Vue to render actual HTML tags, you must use the v-html directive.
<div id="app">
<p>Mustache: {{ rawHtml }}</p>
<p>v-html: <span v-html="rawHtml"></span></p>
</div>
<script>
const app = Vue.createApp({
data() {
return {
rawHtml: '<span style="color: red;">This should be red!</span>'
}
}
});
app.mount('#app');
</script>
Warning: Dynamically rendering raw HTML can easily lead to XSS (Cross-Site Scripting) vulnerabilities! Only use v-html on trusted content.
What prefix do all built-in Vue directives begin with?
If your data variable contains HTML tags (like <b>), which directive must you use to render it properly?