How to Use Interpolation in Vue: Simple Syntax and Examples
In Vue, you use
{{ }} double curly braces for interpolation to display dynamic data inside your HTML templates. Place any JavaScript expression or variable inside {{ }} to render its value in the UI.Syntax
Interpolation in Vue uses double curly braces {{ }} to embed JavaScript expressions or variables inside HTML templates. Vue evaluates the expression inside and updates the DOM with the result.
- {{ expression }}: The expression can be a variable, a simple calculation, or a method call.
- It must be used inside the template section of a Vue component.
- Vue automatically updates the displayed value when the underlying data changes.
vue
<template>
<div>
<p>Hello, {{ name }}!</p>
<p>2 + 3 = {{ 2 + 3 }}</p>
</div>
</template>
<script setup>
const name = 'Vue Learner'
</script>Output
Hello, Vue Learner!
2 + 3 = 5
Example
This example shows how to use interpolation to display a message and a computed value inside a Vue component. The displayed text updates automatically if the data changes.
vue
<template>
<div>
<h1>{{ greeting }}</h1>
<p>Today is {{ day }}.</p>
<p>Random number: {{ randomNumber }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue'
const greeting = 'Welcome to Vue Interpolation!'
const day = new Date().toLocaleDateString('en-US', { weekday: 'long' })
const randomNumber = ref(Math.floor(Math.random() * 100))
</script>Output
Welcome to Vue Interpolation!
Today is Tuesday.
Random number: 42
Common Pitfalls
Common mistakes when using interpolation include:
- Trying to use interpolation inside HTML attributes without binding (use
:attribute="value"instead). - Using interpolation to execute statements or side effects (only expressions are allowed).
- Forgetting that interpolation only works inside templates, not in JavaScript code.
vue
<template>
<div>
<!-- Wrong: interpolation inside attribute (won't work) -->
<img src="{{ imageUrl }}" alt="Image" />
<!-- Right: use v-bind or shorthand : -->
<img :src="imageUrl" alt="Image" />
</div>
</template>
<script setup>
const imageUrl = 'https://vuejs.org/images/logo.png'
</script>Quick Reference
Tips for using interpolation in Vue:
- Use
{{ }}only inside templates to display data. - For HTML attributes, use
v-bindor shorthand:instead of interpolation. - Interpolation accepts JavaScript expressions but not statements.
- Vue updates interpolated values reactively when data changes.
Key Takeaways
Use double curly braces {{ }} to display dynamic data inside Vue templates.
Interpolation works only with expressions, not statements or side effects.
For HTML attributes, use v-bind or : instead of interpolation.
Vue automatically updates interpolated content when data changes.
Interpolation must be inside the template section of a Vue component.