Reputation: 13
I am hoping this is a question that is not answered already, I have looked through the answers and none of them seem to get to the root of my issue, or, I do not have a solid enough grasp on Vue.JS to understand how they can be applied to my situation.
I am using Vue.JS to create a table and filling it with data from a web source. The table can populate just fine, and it works well.
However, I am trying to figure out how I can make each of the rows that are populated with the information a certain color dependent on the value of the data. For example, if the value of the data is between, say, 0 and 12, I want the row to highlight green. If it is between 12 and 30, highlight red, etc.
I have looked extensively into v-bind, and I am pretty confident this is the way to do it. I am familiar with how v-bind basically works, and I can do fairly simple things with it no problem. I just cannot wrap my head around how to combine v-bind with this data and make it function. I hope this is detailed enough.
If more info is needed, please ask.
Thank you!
Here is the table in my html. This is just the outline of my vue instance. These are the classes of what the rows could, depending on the data, be colored.
Upvotes: 0
Views: 8115
Reputation: 43
Try This.
.danger{
background-color: #696969;
}
.success{
background-color: #000000;
}
<tr v-bind:class="{danger:ValueOfTheData< 12,danger:ValueOfTheData < 30}">
<td>RowData</td>
</tr>
Upvotes: 0
Reputation: 11
Try using v-if
<td class="tdlabel" v-if="customerID>=10" style="background: red">ID</td>
<td class="tdlabel" v-if="customerID<0" style="background: green">ID</td>
// more v-else-if
<td class="tdlabel" v-else style="background: you color">ID</td>
Upvotes: 0
Reputation: 3579
You are right about v-binding and you want to bind to a class using the data value to determine the class. I got this to do what you want.
<template>
<table v-for="(stuff, i) in stuffs" :key="i">
<tr :class="getClass(`${stuff.a}`)">
<td>{{stuff.a}}</td>
<td>{{stuff.b}}</td>
<td>{{stuff.c}}</td>
</tr>
</table>
</template>
<script>
export default {
data: () => ({
stuffs: [
{a: 17, b: 'blaa', c: 'hmmm'},
{a: 6, b: 'blah', c: 'hmmm'},
{a: 112, b: 'blah', c: 'hmmm'},
{a: 4, b: 'blah', c: 'hmmm'},
{a: 45, b: 'blah', c: 'hmmm'}
],
class: ''
}),
methods: {
getClass(a) {
if (a<10) {
this.class="first"
return this.class
}
if (a>11 && a< 100) {
this.class = "second"
return this.class
}
else {
this.class = "third"
return this.class
}
}
}
}
</script>
<style scoped>
.first{
background-color: blue
}
.second {
background-color: red
}
.third {
background-color: green
}
</style>
Obviously a pretty basic example but you should be able to get it to do what you want.
Upvotes: 2