Conditional rendering is really easy in vue
- use
v-if/v-else-if/v-elsefor content rendering conditionals - use
v-showfor display and css rendering conditionals
- This example will change a message based on a specific value in the data function
- Template Tag
<div v-if="users[1].likes > users[0].likes">
<p>People like Sam better than Frodo</p>
</div>
<div v-else-if="users[1].likes < users[0].likes">
<p>People like Frodo better than Sam</p>
</>
<div v-else="users[1].likes === users[0].likes>
<p>Frodo and Sam are equally popular amongst the masses</p>
</div>
- Script Tag
data() {
return {
users: [
{
name: 'Frodo Baggins',
likes: 100
},
{
name: 'Samwise Gamgee',
likes: 500
}
]
}
}
- While this example is very simple, using
v-onandcomputedproperties, and node packages such as @nuxt/dayjs, you can do very dynamic rendering
- v-show is great for making things invisible
- it sets display: none when the statement is false
- This example is using the same script content as the v-if/v-else example
- Template Tag
<div v-show="users[0].likes > users[1].likes">
<p>This will return false and not be visible</p>
</div>