4. Conditional Directives and List Rendering With Vue.js
In Vue.js, you can show or hide the HTML Elements based on Conditional fundamentals. Vue.js provides us with a set of core directives to achieve this effect: v-if, v-else, v-else-if.
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>
This example shows you that the a value is more than 10 then the HTML Element paragraph tag will be visible.
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 index
is the index value of item
being 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>
Also use v-bind:key
to Track Elements, When the array order is changed, by default Vue would change the data in each existing element rather than moving the DOM elements to the updated position.
<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>
You can find more info about Vue Conditional and Dynamic Class and Style at Vue Documentation.
Keep watching this and follow us for more tech articles or you can reach out to me for any doubt and suggestions and the next blog in the series will be published soon.
Thanks
Happy Coding!