Vue3 v-text Directive
v-textThe directive is used to update the text content of an element, equivalent to setting the DOM element'stextContentproperty.
Basic Description
v-textThe directive sets the value of its bound expression as the text content of the element. It is the most commonly used text interpolation in Vue templates{{ }}another way of writing.
- Expected Type: string
- Description: Updates the text content of the element, equivalent to setting the textContent property.
Basic Usage
Example
<!-- equivalent to -->
<span>{{ message }}</span>
Example
<div>
<p v-text="greeting"></p>
<p>Using curly braces: {{ greeting }}</p>
</div>
</template>
<script>
export default {
data() {
return {
greeting: 'Hello Vue!'
}
}
}
</script>
Difference between v-text and curly braces
v-textand{{ }}The main differences from curly brace interpolation are:
{{ }}Can be used in text nodes and attributesv-textCan only be used for the text content of an elementv-textWill overwrite the original text content of the element
Example
<span v-text="message">The original text will be overwritten</span>
<!-- Curly braces can preserve other content inside the element -->
<span>Prefix {{ message }} Suffix</span>
Use Cases
1. Simple text binding
When you only need to display text without mixing other content, v-text is a clear choice:
Example
<div>
<h1 v-text="pageTitle"></h1>
<span v-text="userName"></span>
</div>
</template>
<script>
export default {
data() {
return {
pageTitle: 'User Center',
userName: 'Zhang San'
}
}
}
</script>
2. Use with v-once
v-text can be used together with v-once to render only once and not update afterwards:
Example
<div>
<!-- Renders only once; subsequent data changes will not update -->
<p v-once v-text="staticText"></p>
<!-- Will respond to data changes -->
<p v-text="dynamicText"></p>
<button @click="updateText">Update Text</button>
</div>
</template>
<script>
export default {
data() {
return {
staticText: 'Static text, rendered only once',
dynamicText: 'Dynamic text, will update'
}
},
methods: {
updateText() {
this.dynamicText = 'Text updated: ' + new Date().toLocaleTimeString()
}
}
}
</script>
Notes
Overwriting original content: v-text will completely overwrite all text content inside the element. If you only need to update part of the text, you should use curly brace interpolation
{{ }}。
HTML escaping: v-text treats the content as plain text and does not parse HTML tags. If you need to render HTML, you should use the v-html directive.
Example
<span v-text="'<b>bold</b>'"></span>
<!-- If you need to render HTML, use v-html -->
<span v-html="'<b>bold</b>'"></span>
Other Extensions
Vue3 Built-in Directives