Reputation: 11373
##Question
How should I add a conditional statement to my vue project to show a certain element if certain data is not available, and hide a parent.
##Background
I am getting data from a Taco API which includes a recipe. However sometimes that data is empty.
If there is data it currently looks like this
if there is no data, it just has a blank section
##Code
Demo on CodePen
##HTML with vue
<h3>Recipe <span>not available</span></h3>
<p>
<vue-markdown>{{ taco.recipe.title }}</vue-markdown>
</p>
<ul>
<li v-for="item of taco.recipe.items">
<vue-markdown>{{ item }}</vue-markdown>
</li>
</ul>
###JS
data:{
taco: {
name: '',
condiment_name: '',
condiment_recipe_url: '',
recipe: {
title: '',
items: []
}
}
},
##Intent
If Recipe has a value
If recipe {{ item }} value is blank
<span>
in the title that says "not available".<ul>
No solution from similar question vuejs-conditional-handlebars.
I looked the official documentation on conditionals but I am unclear on how to implement it in my project.
Upvotes: 1
Views: 3296
Reputation: 1580
Since you'll be reusing it, you probably want a computed property that stores whether to show the recipe items. In your vue component configuration:
...
computed: {
recipeItemsEmpty () {
return this.taco.recipe && !this.taco.recipe.items.length
}
}
...
With this, we can just use v-if
s to render things conditionally:
<h3>Recipe <span v-if="recipeItemsEmpty">not available</span></h3>
<div v-if="!recipeItemsEmpty">
<p>
<vue-markdown>{{ taco.recipe.title }}</vue-markdown>
</p>
<ul>
<li v-for="item of taco.recipe.items">
<vue-markdown>{{ item }}</vue-markdown>
</li>
</ul>
</div>
Note that I added a div around your p
and ul
elments so the v-if condition could just be used once, but if you really don't want the div you can just put the same v-if condition on both the p
and ul
elements.
Upvotes: 0
Reputation: 17621
You can for example just introduce computed variable to see if its empty or not and use it to hide what u want.
computed: {
recipeNotEmpty: function () {
return this.taco.recipe && this.taco.recipe.items.length > 0
}
},
...
<p v-if='recipeNotEmpty'>
<vue-markdown>{{ taco.recipe.title }}</vue-markdown>
</p>
<ul v-if='recipeNotEmpty'>
<li v-for="item of taco.recipe.items">
<vue-markdown>{{ item }}</vue-markdown>
</li>
</ul>
Upvotes: 0
Reputation: 1585
Try this one below and use v-if, v-else
condition, that should display "no result"
when there is no result in the array.
<h3>Recipe <span>not available</span></h3>
<p>
<vue-markdown>{{ taco.recipe.title }}</vue-markdown>
</p>
<div v-if="taco.recipe.items.length > 0" >
<ul>
<li v-for="item of taco.recipe.items">
<vue-markdown>{{ item }}</vue-markdown>
</li>
</ul>
</div>
<div v-else >
No result found
</div>
Let me know if that works.
Upvotes: 1