I'm trying to filter out some rows in a bootstrap-vue table using a custom filter function.
I wrote a function that takes two arguments - a row object and an empty filter argument, and returns true or false, as in the documentation.
I have tried to use the code provided in this and this answers, but they doesn't work either.
I've also tried to put console.log(row, filter)
into the filterTable method but it doesn't write anything to the console.
<template>
<div>
<b-table
striped hover
:items="items"
:filter=null
:filter-function="filterTable"></b-table>
</div>
</template>
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' }
]
}
},
methods: {
filterTable(row) {
if (row.age >= 40) {
return false;
} else {
return true;
}
}
}
}
It's supposed to display people who are younger than 40 years old, but it displays all the records instead.
The criteria you pass to the filter function must be placed on the filter property in order to be reactive. For example you can add a new property e.g. criteria
to your data object and assign it to :filter
. The filter
property expects a value of type String, RegExp, Object or Array. If you assign a number to it, you will get a warning. The criteria for your filter function will be passed as a second argument.
See example below:
new Vue({
el: "#app",
data() {
return {
criteria: "40",
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'
}
]
}
},
methods: {
filterTable(row, filter) {
if (row.age >= filter) {
return false;
} else {
return true;
}
}
}
})
<link href="https://unpkg.com/[email protected]/dist/bootstrap-vue.css" rel="stylesheet" />
<link href="https://unpkg.com/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<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>
<div id="app">
<div>
<b-table striped hover :items="items" :filter="criteria" :filter-function="filterTable">
</b-table>
</div>
</div>