Conditional rendering means to add or remove elements from the dom if a particular condition is true.
In Vue, we need to use v-if
directive to render the elements conditionally.
Let’s see an example.
<template>
<div>
<!-- v-if="javascript expression" --> <h1 v-if="isActive">Hello Vuejs</h1>
<button @click="isActive= !isActive">Click</button>
</div>
</template>
<script>
export default{
data:function(){
return{
isActive:false
}
}
}
</script>
We can also extend the v-if
directive followed by the v-else
directive.
<h1 v-if="isActive">Hello Vuejs</h1>
<h1 v-else>Hey Vuejs</h1>
If isActive
property is true first h1
element will render otherwise second h1
element will render into the dom.
We can also further extend it using v-else-if
block.
<h1 v-if="isActive">Hello Vuejs</h1>
<h1 v-else-if="isActive && a.length===0">You're vuejs</h1>
<h1 v-else>Hey Vuejs</h1>
v-else-if
directive works like a else-if block in JavaScript.
Sometimes we have to render multiple elements conditionally in such cases we need to group the elements together.
<template>
<div v-if="available">
<h1>Items are available</h1>
<p>More items in the stock</p>
</div>
<div v-else>
<h1>Items are not available</h1>
<p>Out of stock</p>
</div>
</template>
<script>
export default {
data: function() {
return {
available: true
};
}
};
</script>
Here we group the multiple elements in a div
tag.
Example how to use v-if
on <template>
Because v-if
is a directive, it has to be attached to a single element. But what if we want to toggle more than one element? In this case we can use v-if
on a <template>
element, which serves as an invisible wrapper. The final rendered result will not include the <template>
element.
<template v-if="ok">
<h1>Title</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</template>
Another option for conditionally displaying an element is the v-show
directive. The usage is largely the same:
<h1 v-show="ok">Hello!</h1>