Vue.js conditions and loops

Conditional statement


The condition is conditions using the v-if directive:

v-if directive

Use the v-if directive in elements and template:

<div id=" app"> <p v-if="seen">Now you see me</p> <template v-if="ok"> <h1>welookups Tutorial</h1> <p>It’s not just technology, it’s a dream! </p> <p>Hahaha, typing hard! ! ! </p> </template> </div> <script> new Vue({ el: '#app', data: { seen: true, ok: true } }) </script>

Here, the v-if directive will decide whether to insert the p element based on the value of the expression seen (true or false ).

In a string template, like Handlebars , we have to write a conditional block like this:

<!-- Handlebars Template -->
{{#if ok}}


You can add an "else" block to v-if with the v-else directive:

v-else directive

randomly generate a number to determine if it is greater than 0.5, and then output the corresponding information:

<div id=" app"> <div v-if="Math.random() > 0.5"> Sorry </div> <div v-else> Not sorry </div> </div> <script> New vue({ El: '#app' }) </script>


v-else-if Added in 2.1.0, as the name suggests, is used as an else-if block for v-if. Can be used multiple times in chain:

v-else directive

Determine the value of the type variable:

<div id=" app"> <div v-if="type === 'A'"> A </div> <div v-else-if="type === 'B'"> B </div> <div v-else-if="type === 'C'"> C </div> <div v-else> Not A/B/C </div> </div> <script> New vue({ El: '#app', Data: { Type: 'C' } }) </script>

v-else, v-else-if must follow v-if or v-else-if.


We can also use the v-show directive to display elements based on criteria:

v-show directive

<h1 v-show="ok">Hello!</h1>

welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.