Assuming we have a Vue.js
instance defined as:
var vm = new Vue({
el: '#example',
data: {
a: true,
b: false
}
});
You can conditionally render any html element by including the v-if directive; the element that contains v-if will only render if the condition evaluates to true:
<!-- will render 'The condition is true' into the DOM -->
<div id="example">
<h1 v-if="a">The condition is true</h1>
</div>
The <h1>
element will render in this case, because the variable 'a' is true. v-if can be used with any expression, computed property, or function that evaluates to a boolean:
<div v-if="0 === 1"> false; won't render</div>
<div v-if="typeof(5) === 'number'"> true; will render</div>
You can use a template
element to group multiple elements together for a single condition:
<!-- in this case, nothing will be rendered except for the containing 'div' -->
<div id="example">
<template v-if="b">
<h1>Heading</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</template>
</div>
When using v-if
, you also have the option of integrating a counter condition with the v-else
directive. The content contained inside the element will only be displayed if the condition of the previous v-if was false. Note that this means that an element with v-else must appear immediately after an element with v-if.
<!-- will render only 'ELSE' -->
<div id="example">
<h1 v-if="b">IF</h1>
<h1 v-else="a">ELSE</h1>
</div>
Just as with v-if, with v-else you can group multiple html elements together within a <template>
:
<div v-if="'a' === 'b'"> This will never be rendered. </div>
<template v-else>
<ul>
<li> You can also use templates with v-else. </li>
<li> All of the content within the template </li>
<li> will be rendered. </li>
</ul>
</template>