I have a BootstrapVue table that looks like this;
I would like to change the text colour of the number in Age
column to green if Age
>= ID
and to red if Age
< ID
.
Here is the code in a single HTML file.
JavaScript
x
38
38
1
<link href="https://unpkg.com/bootstrap@4.4.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
2
<link href="https://unpkg.com/bootstrap-vue@2.2.2/dist/bootstrap-vue.css" rel="stylesheet"/>
3
4
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
5
<script src="https://unpkg.com/bootstrap-vue@2.2.2/dist/bootstrap-vue.min.js"></script>
6
7
<div id='app'>
8
<b-table :items="items" :fields="fields" bordered>
9
</b-table>
10
</div>
11
12
<script>
13
new Vue({
14
el: '#app',
15
data: dataInit,
16
})
17
18
function dataInit() {
19
20
let init_data = {};
21
22
init_data.fields = [
23
{ key: 'id', label: 'ID'},
24
{ key: 'age', label: 'Age'},
25
{ key: 'first', label: 'First Name'},
26
{ key: 'last', label: 'Last Name'},
27
];
28
init_data.items = [
29
{ id: 18, first: 'Mike', last: 'Kristensen', age: 16 },
30
{ id: 40, first: 'Peter', last: 'Madsen', age: 52 },
31
{ id: 80, first: 'Mads', last: 'Mikkelsen', age: 76 },
32
{ id: 28, first: 'Mikkel', last: 'Hansen', age: 34 },
33
];
34
35
return init_data;
36
}
37
</script>
38
I am using Vue.js v2 and BootstrapVue.
Advertisement
Answer
You can simply achieve it by using _cellVariants
property.
Working Demo :
JavaScript
1
31
31
1
new Vue({
2
el: '#app',
3
data() {
4
return {
5
items: [{
6
id: 18,
7
age: 16,
8
first_name: 'Dickerson',
9
last_name: 'Macdonald'
10
},
11
{
12
id: 40,
13
age: 52,
14
first_name: 'Larsen',
15
last_name: 'Shaw'
16
},
17
{
18
id: 80,
19
age: 76,
20
first_name: 'Geneva',
21
last_name: 'Wilson',
22
},
23
{
24
id: 28,
25
age: 34,
26
first_name: 'Thor',
27
last_name: 'MacDonald'
28
}]
29
}
30
}
31
})
JavaScript
1
7
1
.text-red {
2
color: red;
3
}
4
5
.text-green {
6
color: green;
7
}
JavaScript
1
13
13
1
<script src="https://unpkg.com/vue@2.6.12/dist/vue.min.js"></script>
2
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-vue/2.21.2/bootstrap-vue.min.js"></script>
3
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-vue/2.21.2/bootstrap-vue.min.css"/>
4
<link rel="stylesheet" href="https://unpkg.com/bootstrap@4.5.3/dist/css/bootstrap.min.css"/>
5
<div id="app">
6
<b-table hover :items="items">
7
<template v-slot:cell(age)="{ item }">
8
<span :class="{ 'text-green': item.age >= item.id, 'text-red': item.age < item.id }">
9
{{ item.age }}
10
</span>
11
</template>
12
</b-table>
13
</div>