I have a bootstrap-vue table that looks like this;
Here's the code;
<template>
<div>
<b-table striped hover :items="items" :fields="fields"></b-table>
</div>
</template>
<script>
export default {
data() {
return {
// Note 'isActive' is left out and will not appear in the rendered table
fields: [
{
key: 'last_name',
sortable: true
},
{
key: 'first_name',
sortable: false
},
{
key: 'age',
label: 'Person age',
sortable: true,
// Variant applies to the whole column, including the header and footer
variant: 'danger'
}
],
items: [
{ isActive: true, age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
{ isActive: false, age: 21, first_name: 'Larsen', last_name: 'Shaw' },
{ isActive: false, age: 89, first_name: 'Geneva', last_name: 'Wilson' },
{ isActive: true, age: 38, first_name: 'Jami', last_name: 'Carney' }
]
}
}
}
</script>
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
CodePudding user response:
You can use these two attributes in <b-table>
:
sort-by="age" :sort-desc="true"
Demo :
new Vue({
el: '#app',
data: {
fields: [
{
key: 'last_name',
sortable: true
},
{
key: 'first_name',
sortable: false
},
{
key: 'age',
label: 'Person age',
sortable: true,
// Variant applies to the whole column, including the header and footer
variant: 'danger'
}
],
items: [
{ isActive: true, age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
{ isActive: false, age: 21, first_name: 'Larsen', last_name: 'Shaw' },
{ isActive: false, age: 89, first_name: 'Geneva', last_name: 'Wilson' },
{ isActive: true, age: 38, first_name: 'Jami', last_name: 'Carney' }
]
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/bootstrap-vue.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://unpkg.com/[email protected]/dist/bootstrap-vue.css" rel="stylesheet"/>
<div id="app">
<b-table striped hover sort-by="age"
:sort-desc="true" :items="items" :fields="fields"></b-table>
</div>
---- OR ------
You can bind these attributes dynamically from data property as well with the .sync
option.
<v-data-table
:sort-by.sync="sortBy"
:sort-desc.sync="sortDesc"
></v-data-table>
data () {
return {
sortBy: 'age',
sortDesc: true,
}
}