DEV Community

Pritesh Bhoi
Pritesh Bhoi

Posted on

What is attribute binding in Vue? | Vue Js 3

What is attribute binding in Vue?

At the point when we discuss information restricting in Vue, we imply that the spot where it is utilized or shown in the layout is straightforwardly connected, or bound to the wellspring of the information, which is the information object inside the Vue example. At the end of the day, the host of the information is connected to the objective of the information.

Mustaches cannot be used inside HTML attributes. Instead, use a v-bind directive:

<div v-bind:id="dynamicId"></div>
Enter fullscreen mode Exit fullscreen mode

The v-bind directive instructs Vue to maintain the element's id attribute in sync with the component's dynamicId property. If the bound value is null or undefined, then the attribute could be eliminated from the rendered element.

Shorthand

Because v-bind is so commonly used, it has a dedicated shorthand syntax:

<div :id="dynamicId"></div>
Enter fullscreen mode Exit fullscreen mode

Attributes that begin with : may look a bit different from regular HTML, however it is in truth a valid character for attribute names and all Vue-supported browsers can parse it correctly. In addition, they do now no longer appear in the very last rendered markup. The shorthand syntax is optional, however you may probable appreciate it while you study more about its usage later.

For the rest of the guide, we can be the use of the shorthand syntax in code examples, as that is the most common usage for Vue developers.

Boolean Attributes

Boolean attributes are attributes that, by their presence in an element, can indicate true or false values. For example, one of the most commonly used Boolean attributes is disabled.

V-bind works a bit differently in this case:

<button :disabled="isButtonDisabled">Button</button>
Enter fullscreen mode Exit fullscreen mode

The disabled attribute is included if isButtonDisabled is true.
It is also inserted if the value is an empty string for consistency with <button disabled=""> to protect.
The attribute is ignored for other false values.

Dynamically Binding Multiple Attributes

If you have a JavaScript object that represents multiple attributes, it looks like this:

const objectOfAttrs = {
  id: 'container',
  class: 'wrapper'
}
Enter fullscreen mode Exit fullscreen mode

You can bind them to a single element with v-bind with no argument:

<div v-bind="objectOfAttrs"></div>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)