SyntaxStudy
Sign Up
Vue.js Text Interpolation and Attribute Binding
Vue.js Beginner 1 min read

Text Interpolation and Attribute Binding

Vue templates are valid HTML enhanced with a special syntax. The most fundamental feature is text interpolation using the double-curly-brace syntax `{{ expression }}`. Vue evaluates the JavaScript expression inside the braces and renders its string representation into the DOM. The output is automatically HTML-escaped, which prevents XSS vulnerabilities by default. To dynamically bind a JavaScript value to an HTML attribute you use the `v-bind` directive, most commonly written with its shorthand colon prefix: `:href="url"` instead of `v-bind:href="url"`. The bound expression is evaluated as JavaScript, so you can concatenate strings, call methods, or use ternary operators directly inside the binding. Vue also supports binding multiple attributes at once by passing an object to `v-bind` without an argument: `v-bind="attrs"`. This is extremely useful for higher-order components that forward unknown props down to inner elements without listing every attribute explicitly.
Example
<template>
  <!-- Text interpolation -->
  <h1>{{ title }}</h1>
  <p>Status: {{ isActive ? 'Active' : 'Inactive' }}</p>

  <!-- v-bind shorthand for attributes -->
  <a :href="profileUrl" :title="'Visit ' + username">
    {{ username }}
  </a>

  <!-- Dynamic class and style bindings -->
  <div
    :class="{ active: isActive, 'text-danger': hasError }"
    :style="{ color: textColor, fontSize: fontSize + 'px' }"
  >
    Styled element
  </div>

  <!-- Spread all attributes from an object -->
  <input v-bind="inputAttrs" />
</template>

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

const title      = ref('Vue Template Syntax');
const isActive   = ref(true);
const hasError   = ref(false);
const profileUrl = ref('https://example.com');
const username   = ref('Alice');
const textColor  = ref('royalblue');
const fontSize   = ref(16);
const inputAttrs = ref({ type: 'text', placeholder: 'Enter value', maxlength: 100 });
</script>