Vue v-else-if
Jul 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-if
, Vue 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 }),
// BAD: this template uses v-else-if without an adjacent v-if
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!
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!