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

Once our check is complete, we can default back to our original query code. It will use this


if the select option is not isActive and the data were are filtering on is not a number. If this


is the case, then it will lowercase the field and see if it includes what has been written in the


query box when converted to lowercase as before.


The next stage is to actually compare our numbered data against what has been written in


the query box. To do this, we are going to use the native JavaScript eval function.


The eval function can be a potentially dangerous function and should not be used in


production code without some serious input sanitizing checks, plus, it is less performant


than lengthier alternatives. It runs everything inside as native JavaScript and so can be open


to abuse. However, as we are using this for a dummy application, with the focus being on
Vue itself rather than creating a fully web-safe application, it is fine in this instance. You


can read more about eval in 24 ways:


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

let query = this.filterQuery,
field = person[this.filterField];
if(typeof field === 'number') {
result = eval(field + query);
} else {
field = field.toLowerCase();
result = field.includes(query.toLowerCase());
}

}

This passes both the field and the query to the eval() function and passes the result (either


true or false) to our result variable to determine the visibility of the row. The eval


function literally evaluates the expression and determines if it is true or false. Here's an


example:


eval(500 > 300); // true
eval(500 < 400); // false
eval(500 - 500); // false

In this example, the number 500 is our field, or in this specific example, balance.


Anything that is after that is what is written by our user. Your filtering code is now ready to


go. Try selecting the balance from the dropdown and filtering for users with a balance


higher than 2000.

Free download pdf