Vue v-bind
As you have already observed, a basic Vue setup consists of a Vue instance, which we can access using the v-bind directive or the <div id=”app”> tag with {{ }}.
On this page we will explain the v-bind directive in more depth.
The v-bind Directive
We can connect an HTML attribute to data in the Vue instance using the v-bind directive. This facilitates dynamic attribute value modification.
Syntax
Example
An <img> tag’s src attribute value is derived from the Vue instance data field ‘url’:
CSS Binding
The v-bind directive allows us to dynamically change classes and do in-line styling. In this section, we will walk you through the process in general; later in the tutorial, on the CSS Binding page, we will go into further detail.
Bind style
Using v-bind, you may bind the style attribute to Vue and achieve in-line styling with Vue.
We can build a JavaScript object with the CSS property and value as the value for the v-bind directive:
Example
The ‘size’ Vue data attribute determines the font size.
Text example
If desired, we can also detach the font size unit from the font size number value, like in this case:
Example
The ‘size’ Vue data attribute determines the font size.
Text example
We may alternatively write the CSS property name with CSS syntax (kebab-case) in hyphens, however it is not recommended:
Example
‘font-size’ is the name given to the CSS property fontSize.
Text example
Example
The value of the ‘bgVal’ data field within the Vue instance determines the background color.
Notice the background color on this div tag.
Example
A JavaScript conditional (ternary) expression determines the background color based on the value of the ‘isImportant’ data attribute, which can be either ‘true’ or ‘false’.
Conditional background color
Bind class
We can modify the class attribute by using v-bind.
One possible value for v-bind:class is a variable:
Example
The Vue data property ‘className’ provides the class name.
The class is set with Vue
An object may also be the value of v-bind:class, with the class name only taking effect if it is set to ‘true’.
Example
The assignment of the class attribute is contingent upon the value of ‘true’ or ‘false’ assigned to the class ‘myClass’:
The class is set conditionally to change the background color
When the value of v-bind:class is an object, the class might be allocated depending on a Vue property:
Example
The ‘isImportant’ property determines whether the class attribute is assigned as ‘true’ or ‘false’.
The class is set conditionally to change the background color
Shorthand for v-bind
The shorthand for ‘v-bind:‘ is simply ‘:‘.
Example
Here we just write ‘:‘ instead of ‘v-bind:‘:
The class is set conditionally to change the background color
To keep things clear, we’ll be using the v-bind: syntax throughout this course.