I want to custom filter function on Bootstrap Vue Table. I didn't know what to write to the filter-function prop. I want to search filter.
<template>
<div>
<input
@input.native="tableSearchDebounce"
:input-
:form-group-
v-if="!history" />
<input
v-model="filterTableInputSearchHistory"
:input-
:form-group-
v-else />
<b-table
:items="items"
:fields="fields"
:filter="!history ? filterTableInputSearch : filterTableInputSearchHistory"
@filtered="onFiltered"
/>
</div>
</template>
My methods :
tableSearchDebounce(value) {
clearTimeout(this.$_debounceTimer)
this.$_debounceTimer = this.$nextTick(() => {
this.filterTableInputSearch = value.target._value;
});
},
CodePudding user response:
According to the official documentation
You can provide your own custom sort compare routine by passing a function reference to the prop sort-compare. The sort-compare routine is passed seven (7) arguments, of which the last 4 are optional:
- the first two arguments (a and b) are the record objects for the rows being compared
- the third argument is the field key being sorted on (sortBy)
- the fourth argument (sortDesc) is the order will be displaying the records (true for descending, false for ascending)
You can then write your own sort function using those arguments.
Example :
function sortCompare(aRow, bRow, key, sortDesc) {
const a = aRow[key] // or use Lodash `_.get()`
const b = bRow[key]
return a < b ? -1 : a > b ? 1 : 0
}
Note : In this example, the sortDesc
option is not used.
You can then pass the function through the sort-compare
options of the table
<b-table striped hover :items="items" :sort-compare="sortCompare"></b-table>
#Edit
It seems like you want to search filter using an input and so filter the elements that match the input.
In my opinion, the simplest way to do this would be to use a computed property
to return only the elements that match the input.
This can be done by :
Adding a v-model to the input
<input type="text" v-model="search" />
Creating a computed variable to search for the value you want to filter
computed: {
recordsFiletered() {
return this.records.filter((record) => {
return record.name.toLowerCase().includes(this.search.toLowerCase());
});
},
}
Or you can loop through all of the values of the object if you want to make it generic.
recordsFiletered() {
return this.records.filter((record) => {
return Object.values(record).some((value) =>
value.toString().toLowerCase().includes(this.search.toLowerCase())
);
});
},
Note: This function does not search for property inside of an object
Binding the computed variable to the table
<b-table :items="recordsFiletered"></b-table>
SandBox example: Link here