I have a bootstrap-vue table that looks like this;
Here’s the code;
JavaScript
x
39
39
1
<template>
2
<div>
3
<b-table striped hover :items="items" :fields="fields"></b-table>
4
</div>
5
</template>
6
7
<script>
8
export default {
9
data() {
10
return {
11
// Note 'isActive' is left out and will not appear in the rendered table
12
fields: [
13
{
14
key: 'last_name',
15
sortable: true
16
},
17
{
18
key: 'first_name',
19
sortable: false
20
},
21
{
22
key: 'age',
23
label: 'Person age',
24
sortable: true,
25
// Variant applies to the whole column, including the header and footer
26
variant: 'danger'
27
}
28
],
29
items: [
30
{ isActive: true, age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
31
{ isActive: false, age: 21, first_name: 'Larsen', last_name: 'Shaw' },
32
{ isActive: false, age: 89, first_name: 'Geneva', last_name: 'Wilson' },
33
{ isActive: true, age: 38, first_name: 'Jami', last_name: 'Carney' }
34
]
35
}
36
}
37
}
38
</script>
39
When this table is initially loaded up, I want to specify that the table is sorted according to Person age
column in descending order.
I am using bootstrap-vue and Vue v2.6
Advertisement
Answer
You can use these two attributes in <b-table>
:
JavaScript
1
2
1
sort-by="age" :sort-desc="true"
2
Demo :
JavaScript
1
28
28
1
new Vue({
2
el: '#app',
3
data: {
4
fields: [
5
{
6
key: 'last_name',
7
sortable: true
8
},
9
{
10
key: 'first_name',
11
sortable: false
12
},
13
{
14
key: 'age',
15
label: 'Person age',
16
sortable: true,
17
// Variant applies to the whole column, including the header and footer
18
variant: 'danger'
19
}
20
],
21
items: [
22
{ isActive: true, age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
23
{ isActive: false, age: 21, first_name: 'Larsen', last_name: 'Shaw' },
24
{ isActive: false, age: 89, first_name: 'Geneva', last_name: 'Wilson' },
25
{ isActive: true, age: 38, first_name: 'Jami', last_name: 'Carney' }
26
]
27
}
28
})
JavaScript
1
8
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
2
<script src="https://unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.js"></script>
3
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
4
<link href="https://unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.css" rel="stylesheet"/>
5
<div id="app">
6
<b-table striped hover sort-by="age"
7
:sort-desc="true" :items="items" :fields="fields"></b-table>
8
</div>
—- OR ——
You can bind these attributes dynamically from data property as well with the .sync
option.
JavaScript
1
12
12
1
<v-data-table
2
:sort-by.sync="sortBy"
3
:sort-desc.sync="sortDesc"
4
></v-data-table>
5
6
data () {
7
return {
8
sortBy: 'age',
9
sortDesc: true,
10
}
11
}
12