Attribute Binding

While text interpolation works well between HTML tags, we must use the v-bind directive when working with attributes. In Vue, all directives are prefixed with v- and have special reactive behavior when rendering the DOM.

The span's title attribute will be given that value of the message property of the data object in the code below.

const app = Vue.createApp({
  data: function () {
    return {
      message: 'You loaded this page on ' + new Date().toLocaleString()
    }
  }
})

const vm = app.mount('#app')
<div id="app">
  <span v-bind:title="message">
    Hover your mouse over me for a few seconds
    to see my dynamically bound title!
  </span>
</div>

Values

The value of a bound attribute must be a JavaScript expression. For example, a literal string must be wrap in quotes to be valid.

<!-- This example will cause an error! -->
<div id="app">
  <span v-bind:title="This is my message!">
    Hover your mouse over me for a few seconds
    to see my message!
  </span>
</div>
<!-- This example will work! -->
<div id="app">
  <span v-bind:title="'This is my message!'">
    Hover your mouse over me for a few seconds
    to see my message!
  </span>
</div>

If a combination of a string literal and data property is required, then a template literal or a string concatenation can be used.

const app = Vue.createApp({
  data: function () {
    return {
      size: 150
    }
  }
})

const vm = app.mount('#app')
<div id="app">
  <img v-bind:src="'https://via.placeholder.com/' + size" >
</div>

Shorthand

There is a shorthand for the v-bind directive, which is just the colon (:). So, the previous example could look like this.

<div id="app">
  <img :src="'https://via.placeholder.com/' + size" >
</div>