In Vue.js, v-if and v-else are two essential directives for conditional rendering. With these directives, we can determine whether to render specific HTML elements based on certain conditions. Next, I will explain how to use these directives and provide a concrete example.
Using v-if
The v-if directive evaluates the truthiness of its expression. If the expression evaluates to true, the corresponding element is rendered to the DOM; if it evaluates to false, the element is not rendered.
For example, suppose we have a flag isLoggedIn indicating the user's login status. We can use v-if to display user information:
html<div v-if="isLoggedIn"> <p>Welcome back, user!</p> </div>
If isLoggedIn is true, the welcome message is displayed. If it is false, nothing is displayed.
Using v-else
In Vue, v-else must immediately follow an element with v-if or v-else-if to indicate the content to display when the v-if condition is not met.
Continuing with the previous example, we can add v-else to display a login prompt for unauthenticated users:
html<div v-if="isLoggedIn"> <p>Welcome back, user!</p> </div> <div v-else> <p>Please log in.</p> </div>
In this example, if isLoggedIn is false, the first <div> element is not rendered, and instead the second <div> with v-else is rendered.
Comprehensive Example
Suppose we want to display different navigation menus based on the user's login status:
html<template> <div> <div v-if="isLoggedIn"> <button>Profile</button> <button>Log out</button> </div> <div v-else> <button>Register</button> <button>Login</button> </div> </div> </template> <script> export default { data() { return { isLoggedIn: false // Assuming the user is initially logged out } } } </script>
In this example, depending on the value of isLoggedIn, different button groups are displayed. If the user is logged in, they see "Profile" and "Log out" buttons; if not logged in, they see "Register" and "Login" buttons.
By using v-if and v-else, we can easily control the visibility of UI elements, providing a more intuitive and user-state-appropriate interface.