Suppose I have this table created using bootstrap-vue
.
The code for this table is as follows;
<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>
I would like to add percentage sign as a suffix to the numbers in the Age
column but the column is to remain sortable according to the number value. How can the code be modified to do this?
The code example is extracted from link below; https://bootstrap-vue.org/docs/components/table
I am using vue.js v2.6
CodePudding user response:
If you can directly modify your data, you can simply use Array.prototype.map
:
export default {
data() {
return {
items: [
{ age: 40, first_name: 'Dickerson', last_name: 'Macdonald' },
{ age: 21, first_name: 'Larsen', last_name: 'Shaw' },
{ age: 89, first_name: 'Geneva', last_name: 'Wilson' },
{ age: 38, first_name: 'Jami', last_name: 'Carney' }
].map(item => (
item.age = item.age "%",
item
)),
}
}
}
CodePudding user response:
The straightforward implementation is to use the formatted callback function provided in BootstrapVue to add the percentage sign. Next, set the field property sortByFormatted
to false so that sorting is done according to the unformatted original number values.
Relevant documentation links; https://bootstrap-vue.org/docs/components/table#formatter-callback https://bootstrap-vue.org/docs/components/table#field-definition-reference
Here's the code change needed;
<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',
//Code modification needed. Add the 2 properties below;
"sortByFormatted": false,
formatter: value => {
return (value '%')
},
}
],
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>