We'll see how we can bind the value of attributes in our HTML to JavaScript statements using the v-bind
directive. This allows us to use the data props and JavaScript evaluations to control the appearance and structure of our web applications. We'll also discuss that v-bind:
can be abbreviated to :
.
Instructor: [0:00] So far, we've evaluated our data properties somewhere in our JavaScript. What I want to do next is to use our data properties and bind them to some attributes. I want to put image over here to represent our company event.
[0:11] Let's call it "Image Inventive." Let's get it from Bill Murray, which is a website that gives you images of Bill Murray of whatever size you call it for. Let's call it 200 by 200. We can see that the image is available inside our Vue application. I'm going to put it inside this data, so I'm calling it, right, I'm going to use an image.
[0:30] I want the source to be what we've just defined. Now, if put image inside these quotes, then that's the path that the browser will look for, in order to be able to locate the image.
[0:41] If instead, I put v-bind, that stands for Vue bind, and colon before the attribute I'm targeting, in this case, src. Then Vue will intercept that and replace whatever is inside these quotes with an evaluation, much like in double curly braces, but this time in quotes.
[1:01] If I save this now, we can see that our image has been replaced with our data prop, image has been rendered in our DOM. If you're coming from React, then this is equivalent where we use a single curly brace to interpolate. This is the same behavior.
[1:21] Because we do this so often, v-bind:src, that could get quite tedious. In fact, what we can do is lose the v-bind, just the colon is the signifier to Vue to take whatever is in these quotes, evaluate it, and pass it back as the attribute.
[1:40] We could do something like this. We could say the width was the number of tickets times four. At the moment, that evaluates to zero because it's a string, and we have a signal to Vue that it should interpolate. I haven't put a colon in front of it.
[1:59] There we go. The more tickets, the bigger the picture. It's interesting. We can increase this number of tickets, and as we increase the number of tickets, the size of the image is increasing as well.
[2:09] The colon is telling Vue to take whatever is in the double quotes and evaluate it, much like it already does when it's in double braces, and parse it back to the browser as the value for the attribute in question.