How to bind data in Vue with v-bind

Binding data with v-bind directive enables dynamic HTML attribute assignment using reactive component data for interactive and responsive user interfaces. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented data binding in countless Vue components for dynamic styling, URLs, and interactive element properties. From my expertise, the most effective approach is using v-bind with shorthand syntax for clean and readable attribute binding. This method provides reactive attribute updates that automatically respond to component data changes.

Use v-bind or shorthand : to dynamically bind component data to HTML attributes.

<template>
  <div>
    <!-- Attribute binding -->
    <img v-bind:src="imageUrl" v-bind:alt="imageAlt">

    <!-- Shorthand syntax -->
    <img :src="imageUrl" :alt="imageAlt">

    <!-- Class binding -->
    <div :class="dynamicClass">Dynamic classes</div>
    <div :class="{ active: isActive, disabled: isDisabled }">
      Conditional classes
    </div>

    <!-- Style binding -->
    <div :style="{ color: textColor, fontSize: fontSize + 'px' }">
      Dynamic styles
    </div>

    <!-- Multiple attributes -->
    <button
      :disabled="isLoading"
      :class="buttonClass"
      :title="buttonTooltip"
      @click="handleClick">
      {{ buttonText }}
    </button>

    <!-- URL binding -->
    <a :href="profileUrl">View Profile</a>
  </div>
</template>

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

let imageUrl = ref('/images/avatar.jpg')
let imageAlt = ref('User avatar')
let isActive = ref(true)
let isDisabled = ref(false)
let isLoading = ref(false)
let textColor = ref('#007bff')
let fontSize = ref(16)

let dynamicClass = computed(() => ({
  'btn': true,
  'btn-primary': !isLoading.value,
  'btn-loading': isLoading.value
}))

let buttonClass = computed(() =>
  isLoading.value ? 'btn btn-secondary' : 'btn btn-primary'
)

let buttonText = computed(() =>
  isLoading.value ? 'Loading...' : 'Submit'
)

let buttonTooltip = ref('Click to submit form')
let profileUrl = ref('/user/profile')

let handleClick = () => {
  isLoading.value = !isLoading.value
}
</script>

The v-bind directive connects component data to HTML attributes, automatically updating the DOM when data changes. Use the shorthand : syntax for cleaner templates. Bind objects for classes and styles, and use computed properties for complex attribute logic.

Best Practice Note:

This is the same data binding approach we use in CoreUI Vue components for dynamic user interfaces. Use computed properties for complex attribute calculations to maintain reactivity and performance optimization.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author