Complete Vue.js Course: Mastering from Basic to Advanced
Sobre a Aula

Toggling Visibility with v-show

Hello, students! Welcome to Lesson 4 of Vue.js Directives. Today, we will learn about the v-show directive and how to use it to toggle the visibility of elements.

What is the v-show Directive?

The v-show directive allows toggling the visibility of an element. It is similar to the v-if directive, but with an important difference: the v-show directive does not remove the element from the DOM; it only changes its visibility.

How to Use the v-show Directive?

The basic syntax of the v-show directive is as follows:

<element v-show="condition">

Where:

  • element is the element whose visibility you want to toggle.
  • condition is a JavaScript expression that determines whether the element will be visible.

Example

Let’s see an example of how to use the v-show directive to toggle the visibility of an element:

<div v-show="isLoggedIn">
  <h1>Hello, user!</h1>
</div>

In the example above, the div element will be visible only if the isLoggedIn property is true.

Other Examples

Let’s see some other examples of how to use the v-show directive:

  • Changing the visibility of an element only if the value of a property is greater than a certain value:
<div v-show="age > 18">
  <h1>You are of legal age.</h1>
</div>
  • Changing the visibility of an element only if the user selects an option from a menu:
<div v-show="option === 'option 1'">
  <h1>You selected option 1.</h1>
</div>

JavaScript Expressions in the v-show Directive

You can use JavaScript expressions in the v-show directive to determine whether the element will be visible.

For example, let’s see an example of how to use the v-show directive to change the visibility of an element only if the current time value is greater than 12:

<div v-show="new Date().getHours() > 12">
  <h1>Good afternoon!</h1>
</div>

In the example above, the div element will be visible only if the current time value is greater than 12.

Advantages of the v-show Directive over the v-if Directive

The v-show directive has some advantages over the v-if directive:

  • The v-show directive does not remove the element from the DOM; it only changes its visibility. This can improve your application’s performance.
  • The v-show directive can be used to toggle the visibility of an element dynamically without needing to recreate the DOM.

Conclusion

The v-show directive is a useful tool that can be used to toggle the visibility of elements. It is a good alternative to the v-if directive in some cases.

Challenge

Here’s a challenge for you:

  • Create a Vue.js application that displays a “like” button. The button should be visible only if the user is logged in.

Good luck!

Tip

You can use the v-show directive to create a modal that is only displayed when the user clicks a button.

Entrar na conversa
Rolar para cima