0
0
VueHow-ToBeginner · 3 min read

How to Use v-text Directive in Vue: Simple Guide

In Vue, use the v-text directive to bind plain text content to an element, replacing its inner text safely. It updates the element's text content without parsing HTML, making it a simple way to display dynamic text.
📐

Syntax

The v-text directive binds a JavaScript expression to an element's text content. It replaces the element's inner text with the evaluated value.

  • v-text="expression": Binds the evaluated expression as plain text.
  • The expression can be any valid JavaScript expression or data property.
  • It is a shorthand alternative to using mustache syntax {{ }} for text content.
vue
<div v-text="message"></div>
Output
<div>Hello Vue!</div>
💻

Example

This example shows how to use v-text to display a message from Vue's data. The text inside the div updates reactively when the data changes.

vue
<template>
  <div>
    <h2 v-text="title"></h2>
    <button @click="changeTitle">Change Title</button>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const title = ref('Welcome to Vue!')

function changeTitle() {
  title.value = 'Title Updated!'
}
</script>
Output
<h2>Welcome to Vue!</h2> (initially) After clicking button: <h2>Title Updated!</h2>
⚠️

Common Pitfalls

Common mistakes when using v-text include:

  • Trying to bind HTML content — v-text only inserts plain text, so HTML tags will show as text, not render.
  • Using both v-text and mustache syntax inside the same element — this can cause conflicts.
  • For dynamic HTML, use v-html instead, but be cautious of XSS risks.
vue
<!-- Wrong: HTML tags shown as text -->
<div v-text="htmlContent"></div>

<script setup>
import { ref } from 'vue'
const htmlContent = ref('<strong>Bold Text</strong>')
</script>

<!-- Right: Use v-html for HTML rendering -->
<div v-html="htmlContent"></div>
Output
<div>&lt;strong&gt;Bold Text&lt;/strong&gt;</div> (with v-text) <div><strong>Bold Text</strong></div> (with v-html)
📊

Quick Reference

v-text directive summary:

  • v-text="expression": Inserts plain text content.
  • Replaces element's inner text completely.
  • Does not parse HTML tags.
  • Use for safe, simple text binding.
  • Use v-html for HTML content (with caution).

Key Takeaways

Use v-text to bind plain text safely to an element's content.
v-text replaces the element's inner text completely with the expression's value.
Do not use v-text for HTML content; use v-html instead but carefully.
Avoid mixing v-text and mustache syntax inside the same element.
The directive updates reactively when the bound data changes.