0
0
Vueframework~5 mins

JavaScript expressions in templates in Vue

Choose your learning style9 modes available
Introduction

JavaScript expressions in templates let you show dynamic content easily. They help your webpage change based on data or user actions.

Showing a user's name or age that changes over time
Calculating and displaying a total price from item quantities
Changing text style or content based on a condition
Displaying the current date or time in a readable format
Syntax
Vue
<template>
  <div>{{ expression }}</div>
</template>

Use double curly braces {{ }} to insert JavaScript expressions inside templates.

Expressions can be simple variables, math operations, or function calls.

Examples
Displays the value of the message variable.
Vue
<template>
  <p>{{ message }}</p>
</template>
Shows the value of count plus one.
Vue
<template>
  <p>{{ count + 1 }}</p>
</template>
Shows 'Active' if isActive is true, otherwise 'Inactive'.
Vue
<template>
  <p>{{ isActive ? 'Active' : 'Inactive' }}</p>
</template>
Calls the greet method with name and shows the result.
Vue
<template>
  <p>{{ greet(name) }}</p>
</template>
Sample Program

This Vue component uses JavaScript expressions inside the template to show a greeting, add numbers, and display a message based on a condition.

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

const name = ref('Alice')
const count = ref(3)

function greet(person) {
  return `Hello, ${person}!`
}
</script>

<template>
  <div>
    <p>{{ greet(name) }}</p>
    <p>You have {{ count + 2 }} new messages.</p>
    <p>Status: {{ count > 0 ? 'You have messages' : 'No messages' }}</p>
  </div>
</template>
OutputSuccess
Important Notes

Expressions inside {{ }} should be simple and fast to avoid slowing down rendering.

Avoid complex logic in templates; use methods or computed properties instead.

Summary

Use {{ }} to insert JavaScript expressions in Vue templates.

Expressions can show variables, do math, or run simple functions.

Keep expressions simple for better performance and readability.