How to use conditional render in VueJS?
July 04, 2022Hi Friends đź‘‹,
Welcome To SortoutCode! ❤️
To render the block conditionally, we are using the v-if
directive. It renders the block if the directive’s expression returns the truth value.
Today I am going to show you How do you use conditional rendering in VueJS.
Table of contains
- Define sitename,searchText property for Test
- Using the v-if directive
- Using the v-else-if directive
Let’s start today’s tutorial How do I use conditional rendering in VueJS?
Define sitename,searchText property for Test
Let’s define the sitename in the data of the FirstComponent.vue
component for testing purposes.
FirstComponent.vue
<script>
export default {
name: 'FirstComponent',
data(){
return{
sitename:"sortoutcode.com"
searchText:'',
}
},
}
</script>
Data is used to define properties in a particular component. In a single-file component, data()
is a function that returns a set of properties that have been defined in the function.
we define the three properties that are sitename,searchText.
Using the v-if And v-else directive
we are using the v-if directive to conditionally render the block. The block will only render if the directive’s expression returns a true value.
If the v-if directive expression returns the false value v-else block will render.
You can see the code:
<template>
<div>
<button @click="sitename = !sitename">Toggle</button>
<h1 v-if="sitename">Hi Friends Welcome To SortoutCode</h1>
<h1 v-else>Welcome to Infinitbility</h1>
</div>
</template>
<script>
export default {
name: 'FirstComponent',
data(){
return{
sitename:"sortoutcode.com"
}
},
}
</script>
For now, let’s check the output of the v-if And v-else directive.
Output

Using the v-else-if directive
The v-else-if
as the name suggests the else-if block.It renders on multiple conditions, it works just like the normal ifelse.
<template>
<div>
<input type="text" v-model="searchText" />
<button @click="sitename = searchText">Toggle</button>
<h1 v-if="sitename == 'sortoutcode'">Hi Friends Welcome To sortoutcode.com</h1>
<h1 v-else-if="sitename == 'aguidehub'">Hi Friends Welcome To aguidehub.com</h1>
<h1 v-else-if="sitename == 'infinitbility'">Hi Friends Welcome To infinitbility.com</h1>
</div>
</template>
<script>
export default {
name: 'FirstComponent',
data(){
return{
sitename:"",
searchText:'',
}
},
}
</script>
For now, let’s check the output of the v-else-if directive.
Output

All the best 👍.