v-on and v-show Directives

Part 1, Chapter 6


In this chapter, we're going to be learning about two Vue directives: v-on and v-show.

The v-on directive is used to listen for events (i.e., a button is clicked) and then react to that event.

The v-show directive is used to conditionally show an HTML element. For example, you can use it to only show the full description of a movie if a certain variable is true.

Listening for Events using the 'v-on' Directive

To illustrate how the v-on directive works, let's add a <button> to our webpage:

<main>
    <button>Display Users!</button>
    <h1>List of Users:</h1>
    <ul>
        <li v-for="(user, index) in users" v-bind:key="user">{{ index }}: {{ user }}</li>
    </ul>
</main>

This updated HTML (plus the styling of the button in style.css) will result in a button being added to the webpage:

Add a Button in HTML

However, this button doesn't do anything... yet.

We can add functionality to this button using the v-on directive with the <button> tag:

<main>
    <button v-on:click="displayUsers = true">Display Users!</button>
    <h1>List of Users:</h1>
    <ul>
        <li v-for="(user, index) in users" v-bind:key="user">{{ index }}: {{ user }}</li>
    </ul>
</main>

The v-on directive is applied to the click event associated with the button. When the button is clicked, the logic provided (displayUsers = true) will be executed.

The idea of placing the logic to execute directly in the call to v-on is not my preferred method.

In chapter 7, we'll learn about methods in Vue which is a much better approach to handling logic when using the v-on directive.

Let's add the displayUsers property to the data element of our Vue instance:

<!-- Vue Code -->
<script type="text/javascript">
  const app = Vue.createApp({
    data() {
      return {
        navTitle: 'Vue Course',
        footerMessage: 'testdriven.io',
        users: [
          'user1',
          'employee17',
          'Bob',
          'Sara',
          'Garfield'
        ],
        displayUsers: false  // NEW!!
      }
    }
  });

  const mountedApp = app.mount('#vue-app')
</script>

With the displayUsers property defined, clicking on the button will cause this property to change to true.

Conditionally Displaying HTML Elements Using the v-show Directive

The v-show directive can be used to conditionally display HTML elements if the specified expression is true.

Now that we have a button, let's use it to display the list of users after the button is clicked.

We can use the v-show directive to only show the unordered list (<ul> tag) of users if the displayUsers property is true:

<main>
    <button v-on:click="displayUsers = true">Display Users!</button>
    <h1>List of Users:</h1>
    <ul v-show="displayUsers">
        <li v-for="(user, index) in users" v-bind:key="user">{{ index }}: {{ user }}</li>
    </ul>
</main>

With this update in place, our webpage now looks like this:

v-show Example Before Clicking Button

The webpage now comes up without displaying the list of users. Why? Check out the initial value of the displayUsers property... it is initialized to false.

If you click on the button, then the list of users is displayed:

v-show Example After Clicking Button

Here's the sequence of events that happened:

  • the click event for the <button> was captured (via the v-on directive)
  • it caused the displayUsers property to be changed to true
  • this change caused the unordered list (<ul> tag) to be displayed (via the v-show directive)

Using this combination of Vue directives results in a cool behavior of clicking a button to display content!

The v-on directive is so frequently used in Vue that it has a shortcut... the v-on:click used in the above example can be replaced by @click.

This shorthand is equivalent but provides a more concise usage.

This is purely personal preference, but I do not like this @ shorthand, so I'll be using the full v-on syntax in this course.

Toggling the List of Users

To show how the v-show directive is working, let's change the logic when the button is clicked to change the boolean value of the displayUsers property:

<main>
    <button v-on:click="displayUsers = !displayUsers">Display Users!</button>
    <h1>List of Users:</h1>
    <ul v-show="displayUsers">
        <li v-for="(user, index) in users" v-bind:key="user">{{ index }}: {{ user }}</li>
    </ul>
</main>

With this change, you will see that the list of users can be displayed and hidden by clicking the button over and over again.

Event Modifiers with the 'v-on' Directive

When an event occurs (such as a button being clicked), there are times that you don't want the default behavior, from the browser, of the event to occur; you want to handle the event yourself with the cool Vue code that you created!

Vue provides a set of event modifiers to prevent the default behavior of events from occurring. A common example is preventing the 'Submit' button on a form causing the webpage to submit the form data to the server. This could be handled using the prevent modifier:

<!-- Prevent the default behavior of the Submit button -->
<form v-on:submit.prevent="submitForm">

In this case, the prevent modifier prevents the default behavior of the Submit button and instead the submitForm() function in our Vue code is called (we'll learn about functions in Chapter 6).

Actual Example of Event Modifiers

One of my favorite event modifiers is the once modifier, which will cause an event to only occur once.

Let's add an example to our HTML code:

<main>
    <button v-on:click.once="displayUsers = !displayUsers">Display Users!</button>
    <h1>List of Users:</h1>
    <ul v-show="displayUsers">
        <li v-for="(user, index) in users" v-bind:key="user">{{ index }}: {{ user }}</li>
    </ul>
</main>

The once modifier has been added to the v-on:click event handling. The new functionality of this button is that the first click will cause the list of users to be displayed, but all subsequent calls will have no impact (i.e., there will be no events processed).

This may seem like a simple example, but this is a very powerful feature when submitting form data to make sure a form is only submitted once.

Summary

In this chapter, the v-on and v-show directives were explained and used to add a new feature to our webpage to display a list of users when a button is clicked.

This concept of displaying and hiding data when a button is clicked is a very easy feature to implement thanks to Vue!

Further Reading

For a more complete list of event modifiers, refer to the Vue documentation on Event Modifiers.




Mark as Completed