Understanding directives
In the last lesson, we learned how our Vue app can manage JavaScript state, and also how to get our app to render JavaScript data to the page using interpolations.
Let's now learn another key feature of Vue called "directives".
These are special attributes that you can add to HTML tags that provide certain functionalities.
Here's an example where we have a paragraph tag, and a custom attribute added to it called v-if
.
examples/directives.html
<p v-if="seen">Now you see me</p>
v-if
is a Vue directive. All Vue directives start with this "v-" so they can easily be identified.
As the course progresses, you'll be introduced to a bunch of them including "v-for", v-bind", "v-on" and more.
Also, note that the value assigned to a directive is parsed as a JavaScript expression. So the value seen
is not a string, it's actually an expression.
v-if
Each directive has a purpose, and the purpose of v-if
is to conditionally render the element its applied to.
So if the expression evaluates as true, this paragraph will appear in the DOM, and if it's false, it will not.
Arguments
In this next example, we see a directive called v-bind
. Its job is to bind an HTML attribute or property to a JavaScript expression.
Unlike v-if
, you'll see that this directive has a colon followed by another token. This token is the "argument" and provides extra information to the directive.
In the case of v-bind
, the argument indicates the attribute that the expression should be bound to.
Since this is an anchor tag, it's going to need an href attribute, right?. So the idea of this v-bind
is to assign this JavaScript value to the href attribute.
Let's say, for example, that url
has the value https://google.com
. That's what would get assigned to the href
when it renders.
examples/directives.html
<a v-bind:href="url"></a>
If that all sounds complicated, stick with me and in the next video you'll see how simple and intuitive it actually is when we use a directive in our project.
Click to load comments...