sara97
sara97

Reputation: 401

Vue js: change CSS with v-if and v-else statment

in my Vue JS project i wanted to show data from API and its working good, my only problem is when i showed {{flat.status}} below in my code i wanted to play with CSS for ex: if status==Available let text color be green , and when status==Sold let text color be red and etc ..

is there a way to do it?

<b-th v-for="(flat, index) in Building.flats" :key="index" >
               <p> {{flat.status}} </p>
</b-th>

Upvotes: 1

Views: 1546

Answers (1)

Arc
Arc

Reputation: 1078

Yes! You can do this in a few ways, but the simplest is just to use conditional styles tags. In the :style, just write code!

<p :style=flat.status === 'available' ? 'color: green;' : 'color: 'red'>{{ flat.status }}</p>

If you'd like more CSS control, just use conditional classes.

<p :class="flat.status === 'available' ? 'text-green' : 'text-red'>{{ flat.status }}</p>

<style>
.text-green {
  // CSS here
}
</style>

There are other class binding styles you can look into for more information. They will give you other ways to do all this as well.

For multiple classes (similar example in the link I provided):

<div :class="{ 'text-green': flat.available, 'text-red': flat.sold, 'text-yellow': flat.booked }">{{ flat.name }}</div>

Upvotes: 2

Related Questions