techferment
Published in

techferment

4. Conditional Directives and List Rendering With Vue.js

v-if directive

with the v-if directive, you can add or removes HTML Elements based on the given expression.

<div id="app">
<p v-if="a>10">Number: {{a}}</p>
</div>
<script>
new Vue({
el: "#app",
data:()=>({
a: 5
})
})
</script>

v-else directive

As the name v-else suggests, this directive is used to display content only when the expression adjacent v-if resolves to false.

<div id="app">
<p v-if="a>10">Number: {{a}}</p>
<p v-else>Value of a is not Valid</p>
</div><script>
new Vue({
el: "#app",
data:()=>({
a: 5
})
})
</script>

v-else-if directive

v-else-if can be used when we need more than two options to be checked. This will ensure that only one of the chained items in the else-if chain will be visible.

<div id="app">
<p v-if="a===5">Number: {{a}}</p>
<p v-else-if="a===6">Number: {{a}}</p>
<p v-else>Value of a is not Valid</p>
</div>
<script>
new Vue({
el: "#app",
data:()=>({
a: 5
})
})
</script>

List Rendering

Vue.js provide v-for directive to render a list of items based on an array. The v-for the directive requires a special syntax in the form of (item,index) in items, where items is the source data array and item is an alias for the array element and indexis the index value of itembeing iterated on:

<div id="app">
<ul>
<li v-for="(item, index) in items">{{index}}:- {{item}}</li>
</ul>
</div>
<script>
new Vue({
el: "#app",
data:()=>({
items:[23, 12, 56, 89]
})
})
</script>
<div id="app">
<ul>
<li v-for="(item, index) in items" :key="index">
{{index}}:- {{item}}
</li>
</ul>
</div>
<script>
new Vue({
el: "#app",
data:()=>({
items:[23, 12, 56, 89]
})
})
</script>

Using v-for with Objects

You can loop over the values in an objectItems object from the data in Vue Instance. You can achieve this with v-for directive in the element that should be repeated.

<div id="app">
<ul>
<li v-for="(item, index) in items" :key="index">
{{index}}:- Name: {{item.name}} and Age: {{item.age}}
</li>
</ul>
</div>
<script>
new Vue({
el: "#app",
data:()=>({
items:[
{ name:"s1", age:12 },
{ name:"s2", age:14 },
{ name:"s3", age:16 }
]
})
})
</script>

--

--

Our mission is to equip our community members with practical skills, enabling them to communicate their insights and drive innovative solutions effectively. We are a thriving engineering community, dedicated to fostering a network of inquisitive individuals.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vrijraj Singh

Google Developer Expert for Web Technologies & Firebase | Developer Advocate | GDG Organizer for GDG Jalandhar