← Back to Vue.js Course | Chapter 2: Template Syntax | Lesson 2 of 7

v-bind

v-bind connects an HTML attribute to your data, and its shorthand is a single colon.

In this page:

  1. v-bind
Syntax
markup
<img v-bind:src="expression">
<a :href="expression">link</a>
<button :disabled="condition">text</button>

v-bind

Use v-bind:attr or :attr to bind attributes such as src, href, disabled and class to expressions. Binding to false, null or undefined removes the attribute.

Object syntax binds several attributes at once, and class and style have special helpers for objects and arrays.

Note: Write :id="id" as the short form of v-bind:id="id".

Example: v-bind

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
  <a :href="url" :title="label">Docs</a>
  <button :disabled="busy">Save</button>
  <p :class="{ active: isActive, muted: !isActive }">status</p>
  <p :style="{ color: color, fontSize: size + 'px' }">styled</p>
</div>
<script>
  Vue.createApp({
    data() { return { url: "https://vuejs.org", label: "Vue docs", busy: true, isActive: true, color: "green", size: 18 }; },
  }).mount("#app");
  Vue.nextTick(() => {
    const a = document.querySelector("a");
    console.log(a.getAttribute("href"), document.querySelector("button").disabled, document.querySelector("p").className);
  });
</script>
</body>
</html>

<!-- Output:
Rendered: DocsSavestatusstyled
console: https://vuejs.org true active
-->
Live Example
Related Topics
Common Mistakes
  1. Writing attr="{{ value }}" which does not work
  2. Forgetting boolean attributes are removed when false
  3. Binding class strings instead of objects
Chapter Summary
  • :attr is shorthand for v-bind:attr
  • false or null removes an attribute
  • Object syntax binds many attributes
  • Class and style accept objects
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.