HTML Attribute Binding in Vue
We know how to render data in the DOM with Vue 3, and now it's time to take a closer look at how we can bind HTML attributes to our Vue data.
This is achieved with Vue's v-bind directive and would let us change the href (or any other HTML attribute) of a link or swap out an image if we need to.
NOTE: for the link to work properly you should provide the protocol in the input (http:// or https://)
LESSON TRANSCRIPT
View uses the double mustache syntax to render data to the DOM. But how would we make an element attribute like an href dynamic? Well, with the vbind directive, we can couple any HTML attribute to our reactive references. For example, let's add a link to our template.
Then we'll use vbind on the href. referencing the new item reactive ref that's bound to our text input. And finally, we'll give it the label dynamic link. Awesome.
Now if we add a URL to our input, we should be able to click it, and it will take us wherever we've typed in. com. io. Awesome.
This is an incredibly powerful feature of Vue. Now we can build templates where any attribute responds to our data. For our shopping list app, let's toggle the disabled attribute on our Save Item button when there isn't any content in our input. That way, we won't accidentally add blank data to our shopping list.
We'll start by clearing out the example link. And then we can add a vbind to our button. We'll say that the button is disabled when the length of new item is strictly equal to zero. Now, our button won't work until we have some content in our input.
Awesome. This is also a great technique for enforcing minimum character requirements on our inputs as well. I'll just change out the triple equals zero here to a less than five. In other words, our button will be disabled when the input is less than five characters long.
You can see our button is grayed out here. We'll start typing. And as soon as we hit five, the button lights up and we can add the item to our list. Very nice.
Finally, just like V on has a shorthand syntax with the at symbol, V bind can also be shortened to just a colon. And once again, this is probably how you'll see it used most often. While we can use vbind with every attribute, there are some special use cases. And we'll cover those in the next lesson.
This transcript is generated automatically from the lesson video. Spotted an inaccuracy? Let us know at team@vueschool.io.
- Chapter 1
