0

Vue v-if and v-else

 2 years ago
source link: https://masteringjs.io/tutorials/vue/v-if-else
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Vue v-if and v-else

Jul 13, 2022

To conditionally render something in Vue, you should use v-if and v-else directives. Simply pass an expression to the v-if directive, and the block will render if the expression is true. You can also use v-else, which will render if the preceeding v-if expression evaluates to a falsy value. Below is a live example and the necessary code to replicate it:

const app = Vue.createApp({
  data: () => ({ display: true }),
  methods: {
    toggleText() {
      this.display = !this.display;
    }
  },
  template: `
  <div>
    <h1 v-if="display">Hello!</h1>
    <h1 v-else>Goodbye :(</h1>
    <button @click="toggleText()">Toggle</button>
  </div>
  `
}).mount('#content');

Hello!

An element with a v-else directive must immediately follow an element with a v-if or v-else-if directive. Otherwise, the v-else element will always render, and Vue will log the below warning to the console:

[email protected]:1616 [Vue warn]: Template compilation error: v-else/v-else-if has no adjacent v-if or v-else-if.
3  |        <h1 v-if="display">Hello</h1>
4  |        <h1>World</h1>
5  |        <h1 v-else>Goodbye</h1>
   |        ^^^^^^^^^^^^^^^^^^^^^^^
6  |        <button @click="toggleText()">Toggle</button>
7  |      </div> 
  at <App>

Below is a live example of a v-else without an adjacent v-if. Notice that the "Goodbye" h1 renders regardless of the display value.

Hello

World

Goodbye

const app2 = Vue.createApp({
  data: () => ({ display: true }),
  methods: {
    toggleText() {
      this.display = !this.display;
    }
  },
  // BAD: the below template has a `v-else` that isn't adjacent to a `v-if`
  template: `
  <div>
    <h1 v-if="display">Hello</h1>
    <h1>World</h1>
    <h1 v-else>Goodbye</h1>
    <button @click="toggleText()">Toggle</button>
  </div>
  `
}).mount('#content2');

Vue School has some of our favorite Vue video courses. Their Vue.js Master Class walks you through building a real world application, and does a great job of teaching you how to integrate Vue with Firebase. Check it out!


More Vue Tutorials


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK