Using v-bind in Vue

Aug 9, 2019

In Vue, v-bind lets you bind an HTML attribute to a JavaScript expression. There are two broad use cases for this one-way data binding:

Binding to Built-in Attributes

You can use v-bind to bind built-in HTML attributes to JavaScript expressions. For example, you can make a link whose href is bound to a data field. When the link field changes, so does the href.

const app = new Vue({
  data: () => ({ link: 'http://google.com' }),
  // Initially, the link will go to Google...
  template: `
    <a v-bind:href="link">My Link</a>
  `
});
// Now, the link will go to Twitter.
app.$data.link = 'http://twitter.com';

You can use this syntax for some cool use cases, including dynamic inline style attributes.

const app = new Vue({
  data: () => ({ color: 'blue' }),
  // Initially, will show "blue text" in blue font.
  template: `
    <div v-bind:style="{ color }">{{color}} text</div>
  `
});
// Now, it will show "green text" in green font.
app.$data.color = 'green';

Props

You can also use v-bind to pass props to child components.

// `props` is an array of prop names this component accepts. If you
// don't explicitly list a prop in `props`, you won't be able to use
// it in your template.
Vue.component('hello', {
  props: ['name'],
  template: '<h1>Hello, {{name}}</h1>'
});

// The app tracks `name` as internal state, and there's an input to
// modify `name` using `v-model`. Then, `v-bind:name` passes `name` as
// a prop to the `hello` component.
const app = new Vue({
  data: () => ({ name: 'World' }),
  template: `
    <div>
      <div>
        <input v-model="name"></input>
      </div>
      <hello v-bind:name="name"></hello>
    </div>
  `
});

Shorthand

The v-bind part of v-bind:prop is optional. You can also use :prop. Most large Vue codebases use :prop and avoid typing out v-bind.

const app = new Vue({
  data: () => ({ link: 'http://google.com' }),
  // `:href` is the same ad `v-bind:href`, just more concise.
  template: `
    <a :href="link">My Link</a>
  `
});

Vue School has some of our favorite Vue video courses. Their Vue.js Master Class walks you through building a real world application, and does a great job of teaching you how to integrate Vue with Firebase. Check it out!


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Vue Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!