Blog>
Snippets

Conditionally rendering VNodes with v-if

Explains how to conditionally render VNodes using the `v-if` directive and how to leverage `v-else` and `v-else-if` for additional logic.
Vue.createApp({
  data() {
    return {
      userLoggedIn: true,
      userName: 'Alice'
    };
  }
}).mount('#app');
Initializes a Vue application with a data property 'userLoggedIn' to control the conditional rendering and a 'userName' to display.
<div id="app">
  <p v-if="userLoggedIn">Welcome, {{ userName }}!</p>
  <p v-else>Please log in.</p>
</div>
Uses v-if to conditionally render a welcome message if 'userLoggedIn' is true, otherwise renders a prompt to log in using v-else.
<div id="app">
  <p v-if="userLoggedIn">Welcome back, {{ userName }}!</p>
  <p v-else-if="userAttemptedLogin">Login attempt failed, please try again.</p>
  <p v-else>Please log in to continue.</p>
</div>
Expands the previous example with a v-else-if to provide an additional conditional block that is rendered when 'userLoggedIn' is false but 'userAttemptedLogin' is true.