1
votes

I'm using Bootstrap-Vue to display information in a table. Each element displayed has two fields ( name and age ). By now, I can filter by one field (either name OR age), but I want to have two inputs to filter by both of them.

So if I type "Dav" at name and "2" at age, I want to display all person with 'Dav' at the name ang '2' on his/her age.

I've tried passing an array (['age', 'name']) and an object (name: 'name', age:'age') to :filter, but nothing works.

I've forked an example and simplify it. Here you'll have two inputs, one for name and another for age. You can filter by name (:filter="name") but not by age. I can switch 'age' for 'name' and it will work, but only for 'age'.

Here's the code:

[https://jsfiddle.net/esom2f9p/2/][1]

TL;DR: The table filters by 'name' but should filter by 'name' and 'age'. I want to know how to filter by two or more fields.

2

2 Answers

2
votes

I used computed fields and the filter-function prop

<b-table bordered show-empty striped stacked="md" no-provider-filtering 
class="management-list" ref="table"
v-model="filteredItems"
:items="tableItems"
:fields="fields"
:current-page="currentPage"
:per-page="perPage"
:filter="filter"
:filter-function="filterTable"
:sort-by.sync="sortBy"
:sort-desc.sync="sortDesc"
@filtered="onFiltered">
</b-table>

Set filter to null when all variables are null. If at least one is not null, then set it to an array. In my example I just use 2 variables.

computed: {
    filter: function() {
        if (this.filterVarOne === null && this.filterVarTwo ===  null){
            return null;
        }

        return [this.filterVarOne , this.filterVarTwo];
    }
},

Then the filter function will be called when one of the variables is set.

methods: {
    filterTable: function(tableRow, filter){
        if (filter[0] !== null && filter[1] !== null){
            //both filters set
            return tableRow.columnOne == filter[0] && 
                   tableRow.columnTwo == filter[1];
         }
        else {
            return tableRow.columnOne == filter[0] ||
                tableRow.columnTwo == filter[1];
        }

    }
},

From bootstrap vue documentation

The filter function will be passed two arguments:

the original item row record data object. Treat this argument as read-only. the content of the filter prop (could be a string, RegExp, array, or object)

1
votes

You can use the computed property for filtering data.

Refer this -

https://jsfiddle.net/thbn816x/5/