Conditionals in Vue — Transcript

Transcript of the free Vue.js lesson Conditionals in Vuewatch the video lesson.

Sometimes it's necessary to only render HTML when certain conditions are true. Therefore, Vue provides us with the vif and velse directives that let us conditionally render elements. All right, we can use this in our shopping list app to show a message if there are no items in the list. Let's start by commenting out the items in the items array.

In our template, we can now add a p tag with a v if that only shows when there are no items. On the right hand side, we can see that our empty state message is now showing. Excellent. And if we add a new item, then it goes away.

Great. While this is a great example of conditionally toggling one element, What if we wanted to show two different states? Let's see how to do that by hiding the form when we're not using it. Let's start by adding and editing reactive ref.

And I'll initialize it to false. Now we can add a vif to our form wrapper. We can set it to show when editing is true. Over on the right-hand side, we can see that our form is no longer there because the condition is false.

If we inspect the element, we can see that our form is actually missing completely from the DOM. That's because VEF actually toggles the existence of that element on the page. All right, let's add some buttons now to show and hide the form. We can do that by wrapping our H one in a div with the class of header.

And note that this is really just for styling. Then we can add two buttons, one for cancel and one for add item. Now we can make use of the V else directive. When we use V if and V else together, we can dynamically toggle elements based on how our conditional evaluates.

In this case, we'll want to show the cancel button when editing is true. Otherwise, we want the add item button to show. Sweet. Now we're ready to add another method that will be responsible for changing the value of our editing reactive ref.

I'll call it doEdit. Then I'll pass through an argument, e, short for editing, and set our editing reactive ref to it. Let's also clear out our new item so that we don't persist any halfway finished items. Now we just need to add that to our buttons using the V on directive.

And of course, cancel will be do edit with the argument of faults and add item will be do edit with the argument of true. Over on the right hand side, you can see that clicking the buttons now toggles the form.