- Learn by example
Make an RPG
Vue Implementations

Example of Vue v-bind

Attributes are the things within the tags, for instance id, class, or title

Think of v-bind as a way to dynamically change attribute strings. Typically you will change attributes like: style, class, title, etc.

Attriutes, like the span title can be dynamically set:

<div id="app-2"> <span v-bind:title="message"> Hover your mouse over me for a few seconds to see my dynamically bound title! </span> </div>
var app2 = new Vue({ el: "#app-2", data: { message: "You loaded this page on " + new Date().toLocaleString() } });
Try changing title to something else like: my_attribute, etc

Let's dynamically set the class. You can set isActive to false in the console by doing app2.isActive = false. When you do that, the color will no longer be red.

var app2 = new Vue({ el: "#app-2", data: { isActive: true } });
.active { color: red; }
<div id="app-2"> <span v-bind:class="{ active: isActive }"> Hello </span> </div>
Change isActive to false in the javascript.
Try changing the name of the class from 'active' to something else.

You can set multiple classes in v-bind as well as have regular classes, like so:

var app2 = new Vue({ el: "#app-2", data: { isActive: true, isLarge: true } });
<div id="app-2"> <span class="additional" v-bind:class= "{ active: isActive, large: isLarge }"> Hello </span> </div>

The presence of curly braces tells it to evaluate the truthiness if isActive and place active there. So, you can set the class dynamically using a regular v-bind without curly braces:

.blue { color: blue; }
var app2 = new Vue({ el: "#app-2", data: { myClass: "blue" } });
<div id="app-2"> <span v-bind:class="myClass"> Hello </span> </div>


There are two ways to v-bind styles.

1. You can place style objects directly into a v-bind:style

var app = new Vue({ el: "#app" });
<div id="app-2"> <span v-bind:style= '{ fontSize: "15px", color: "orange" }'> Hello </span> </div>

2. You can use a data object to specify the style

var app = new Vue({ el: "#app", data: { styleObj: { fontSize: "18px", color: "purple", fontWeight: "bold" } } });
<div id="app"> <span v-bind:class="styleObj"> Hello </span> </div>

You can specify multiple style objects like so:

var app = new Vue({ el: "#app", data: { base: { fontSize: "15px", color: "orange" }, override: { color: "blue", border: "1px solid black" } } });
<div id="app"> <span v-bind:class= "[ base, override ]"> Hello </span> </div>

The second object overrides the first once, hence the color of the text is blue, not orange.

In the next lesson, we will learn about Example of Vue Components

Get the Latest Tutorial Updates
<< >>