Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Displaying, Looping, Searching, and Filtering Data Chapter 2

Upon pressing save, your text should disappear. That is because the tag is being


conditionally rendered based on the value, which is currently false. If you open up your


JavaScript console and run the following code, your element should reappear:


app.isVisible = true

v-if doesn't just work with Boolean true/false values. You can check whether a data


property is equal to a specific string:


<div v-if="selected == 'yes'">Now you see me</div>

For example, the preceding code checks whether a selected data property is equal to the


value of yes. The v-if attribute accepts JavaScript operators, so can check not equals,


bigger, or less than.


The danger here is that your logic starts to creep into your View away from your
ViewModel. To combat this, the attribute also takes functions as a value. The method can be


as complicated as required but ultimately must return a true if you wish to show the code


and a false if not. Bear in mind that if the function returns anything other than a false


value (such as 0 or false) then the result will be interpreted as true.


This would look something like this:


<div v-if="isSelected">Now you see me</div>

And your method could be as this:


isSelected() {
return selected == 'yes';
}

If you don't wish to completely remove the element and only hide it, there is a more


appropriate directive, v-show. This applies a CSS display property rather than


manipulating the DOM – v-show is covered later in the chapter.


v-else


v-else allows you to render an alternative element based on the opposite of the v-if


statement. If that results in true, the first element will be displayed; otherwise, the element


containing v-else will.

Free download pdf