Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Displaying, Looping, Searching, and Filtering Data Chapter 2

The first step in doing this is to only apply this type of filtering when it is the balance


field. We can approach this two ways – we can either check that the field name is balance,


similar to how we check the isActive field, or we can check the type of data we are


filtering on.


Checking against the field name is simpler. We can do an else if() in our method or


even migrate to a switch statement for easier reading and expansion. The alternative of


checking the field type, however, is more scalable. It means we can expand our dataset with


more numeric fields without having to extend or change our code. It does mean, however,
that there will be further if statements in our code.


What we will do first is alter our storing method, as we don't want to necessarily lowercase
the field or query:


if(this.filterField === 'isActive') {
result = this.filterUserState === person.isActive;
} else {

let query = this.filterQuery,
field = person[this.filterField];

}

The next step is to establish the type of data in the field variable. This can be established by,


once again, using the typeof operator. This can be used in an if statement, to check


whether the type of field is a number:


if(this.filterField === 'isActive') {
result = this.filterUserState === person.isActive;
} else {

let query = this.filterQuery,
field = person[this.filterField];

if(typeof field === 'number') {
// Is a number
} else {
// Is not a number
field = field.toLowerCase();
result = field.includes(query.toLowerCase());
}

}
Free download pdf