Vue Conditionals using v-if

In our previous tutorial we have successfully achieved the rendering/displaying of array objects in our application using the Loop feature of Vue.js. In this tutorial, we are going to discuss Conditions. It is a feature of Vue that is easy to grasp. We will then take a summary discussion after we have accomplished our task.

To get started, let us take the similar application from the previous tutorial which is the Todo List App. From the previous tutorial, we only listed the task list. Now, we will enhance our previous application by initializing an item list such that when we click, it will show the list of tasks. To make it short, we are going to have an item similar to the image below.

conditionals using v-if

After we have created our first item parent that is clickable and will show our task list, let us open our app.js and declare a new variable that will handle a boolean value which means it is either true or false. Here is the full example.

conditionals using v-if

We initialize a false value assuming that nothing will be shown up in our display. Now, let us open our html file and set a condition.

conditionals using v-if

This is our first table that will handle and set the condition. The other table will look like the image below.

conditionals using v-if

Now make a code similar to the above image and refresh your browser. Click on View My Task and see what will happen.

conditionals using v-if

That’s right! The above example is the output after you have triggered an event click on your View My Task element.  

Let us have a brief discussion on how did we got the final results. First, you may ask – what does the v-if condition do to our html elements? The explanation is very simple – in the above example, it only hides a DOM element when a certain condition is met. For example, let us take the first table and analyze the first v-if condition. Remember that in our app.js, we have set the default value by false. In our table, notice that we have set a logical operator (!) which means that the value is false. From there we can assume that the default value false is equal to a NOT value (false) to make it simple;

false == false ? TRUE

Since the condition is true, Vue.js shows up the View My Task as default in our display. Now let’s take a look at our v-on:click event. Notice that we have changed the default value false into true which means, it will hide our first table and display the next table. This is how we achieved the result in our application.

On our next chapter, we are going to learn how to handle the two way binding and handling of user input.

Subscribe Now and Upgrade Your Skills Today!
Sign up now and have the latest tech tutorials delivered straight to your mailbox.

PLUS: Get exclusive member-only discounts (up to 80% OFF!!) on our top tech courses in Udemy!
We hate spam. Your email address will not be sold or shared with anyone else.