Reputation: 75
I just want to add a class to a using a conditional. I'm trying this code:
<template>
<div class="recipe" v-if="recipe.featured == 'true'" :class="recipe.featured">
<button class="delete-recipe">
<img src="@/assets/delete-button.svg" alt="Eliminar" title="Eliminar" />
</button>
<h2 class=".recipe-title">{{ recipe.title }}</h2>
<div class="recipe-image"><img :src="recipe.image" /></div>
<div class="recipe-info">
<div class="recipe-info-item">
<span class="recipe-info-label">Servings:</span>
<span class="recipe-info-value"> {{ recipe.servings }} </span>
</div>
I want to add the class "recipe.featured" to the div when recipe.featured props is true. I have json where I have my dates.
The css of recipe.featured is easy. I just want to paint the background. But at this moment is not working.
Any help?
Thanks.
Upvotes: 4
Views: 8504
Reputation: 3829
You can pass class conditionally using a ternary operator vue.js documentation
Example :
<div :class="recipe.featured ? 'myFirstClass' : 'mySecondClass'">
If you want to pass a class anyway you can pass it to a different class
<div :class="recipe.featured ? 'myFirstClass' : 'mySecondClass'" class="myClass">
Note: if you don't want to pass a class just put a blank class like* :class="recipe.featured ? 'myFirstClass' : ''
Upvotes: 5
Reputation: 173
For bools you can just do:
v-if="recipe.featured" if you want it to conditionally appear or not.
The problem with this:
<div class="recipe" v-if="recipe.featured == 'true'" :class="recipe.featured">
What you're saying here is the class = recipe, it will only appear if the recipe featured is equal to a string of true, and if it does equal a string of true, it will appear.
In terms of your query, have you tried:
<div :class="{ recipe.featured: recipe.featured }"></div>
The first recipe.featured is your property, and the second is your class. If your property evaluates to true, it will show the recipe.featured class. You could also add an alternative for if it evaluates to false, for example:
<div :class="[recipe.featured ? recipe.featured : unfeaturedclass]"></div>
https://v2.vuejs.org/v2/guide/class-and-style.html
Probably quite a few ways to achieve your result but i hope this helps!
Upvotes: 0