我有一个带有tbody并使用Vuejs的表:
<tbody>
<tr v-for="(item,i) in data" :key="i">
<th scope="row"></th>
<td>{{item.dwg}}</td>
<td>{{item.name}}</td>
<td>{{item.ValueOfDay1}}</td>
<td>{{item.ValueOfDay2}}</td>
<td>{{item.ValueOfDay3}}</td>
</tr>
</tbody>
我想使用v-if更改<td>
元素的样式:
if item.ValueOfDay1 = 10 --> background-color of <td> is red,
if item.ValueOfDay1 = 10.1 --> background-color of <td> is blue,
if item.ValueOfDay1 = 10.2 --> background-color of <td> is green.
我该怎么做?
答案 0 :(得分:-1)
根据以下条件添加动态样式-> :class =“ item.ValueOfDay1 == 10?'bgRed':item.ValueOfDay1 == 10.1?'bgBlue':item.ValueOfDay1 == 10.2?'bgGreen':''”
<tbody>
<tr v-for="(item,i) in data" :key="i">
<th scope="row"></th>
<td>{{item.dwg}}</td>
<td>{{item.name}}</td>
<td :class="item.ValueOfDay1 == 10 ? 'bgRed' : item.ValueOfDay1 == 10.1 ? 'bgBlue' : item.ValueOfDay1 == 10.2 ? 'bgGreen' : ''">{{item.ValueOfDay1}}</td>
<td :class="item.ValueOfDay1 == 10 ? 'bgRed' : item.ValueOfDay1 == 10.1 ? 'bgBlue' : item.ValueOfDay1 == 10.2 ? 'bgGreen' : ''">{{item.ValueOfDay2}}</td>
<td :class="item.ValueOfDay1 == 10 ? 'bgRed' : item.ValueOfDay1 == 10.1 ? 'bgBlue' : item.ValueOfDay1 == 10.2 ? 'bgGreen' : ''">{{item.ValueOfDay3}}</td>
</tr>
</tbody>
CSS
.bgRed{
background:red;
}
.bgBlue{
background:blue;
}
.bgGreen{
background:green;
}
答案 1 :(得分:-1)
这是解决您问题的方法,希望对您有帮助
https://jsfiddle.net/mathmelo/fjs9x7by/3/#
HTML
<table>
<tbody>
...
<td :class="changeBackgroundColor(item.ValueOfDay1)" >{{item.ValueOfDay1}}</td>
...
</tr>
</tbody>
Vue
new Vue({
el: '#app',
data: {
data: [
{dwg: 0, name: 'test' , ValueOfDay1: 10, ValueOfDay2: 20, ValueOfDay3: 30},
{dwg: 0, name: 'test2' , ValueOfDay1: 10.2, ValueOfDay2: 20, ValueOfDay3: 30},
{dwg: 0, name: 'test3' , ValueOfDay1: 10.1, ValueOfDay2: 20, ValueOfDay3: 30}
]
},
methods: {
changeBackgroundColor(valueOfDay) {
//Get the decimal part of the number
decimals = valueOfDay - Math.floor(valueOfDay);
switch(decimals.toFixed(1)){
case '0.0' : return 'red'
case '0.1' : return 'blue'
case '0.2' : return 'green'
}
}
}
});
和CSS
.red {
background-color: red;
}
.blue {
background-color: blue;
}
.green {
background-color: green;
}