September 26, 2022

Robotic Notes

All technology News

Vue v-else-if – Mastering JS

1 min read


July 18, 2022

Vue provides a v-else-if directive that you can use with v-if analogous to using else if {} with if {}.

const app = Vue.createApp({
  data: () => ({ value: 1 }),
  template: `
  <div>
    <div>
      <h1 v-if="value > 0">Hello</h1>
      <h1 v-else-if="value > 1">There</h1>
      <h1 v-else-if="value > 2">World</h1>
    </div>
    <button @click="value++">Increment</button>
  </div>
  `
}).mount('#content');

v-else-if must follow a v-if. If you use v-else-if without v-ifVue will print the following warning to the console.

[Vue warn]: Template compilation error: v-else/v-else-if has no adjacent v-if or v-else-if.

Below is an example of using v-else-if without v-if. If you open the console on this page, you’ll see a “Template compilation error” warning from Vue.

const example = Vue.createApp({
  data: () => ({ value: 2 }),
  
  template: `
  <div>
    <div>
      <h1 v-else-if="value > 1">There</h1>
      <h1 v-else-if="value > 2">World</h1>
      <h1 v-else-if="value > 3">Hello</h1>
    </div>
    <button @click="value++">Increment</button>
  </div>
  `
}).mount('#example');

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



Source link