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

Before we move on, we need to add some error checking. If you have your JavaScript


console open, you may have noticed an error when you typed the first greater or less than.
This was because the eval function is unable to evaluate X > (where X is the balance). You


may have also been tempted to type $2000 with the currency and realized this doesn't


work. This is because the currency is applied while rendering the view, whereas we are


filtering the data before this is rendered.


In order to combat these two errors, we must remove any currency symbols typed in the


query and test our eval function before relying on it to return the results. Remove the


currency symbol with the native JavaScript replace() function. If it changes, uses the


currency symbol stored in the app, rather than hardcoding the currently used one.


if(typeof field == 'number') {
query = query.replace(this.currency, '');
result = eval(field + query);
}

We now need to test the eval function so it does not throw an error with every key


pressed. To do this, we use a try...catch statement:


if(typeof field == 'number') {
query = query.replace(this.currency, '');
try {
result = eval(field + query);
} catch(e) {}
}

As we don't want to output anything when an error is entered, we can leave the catch


statement empty. We could put the field.includes(query) statement in here, so it falls


back to the default functionality. Our full filterRow() method now looks like this:


filterRow(person) {
let result = true;
if(this.filterField) {

if(this.filterField === 'isActive') {

result = this.filterUserState === person.isActive;

} else {

let query = this.filterQuery,
field = person[this.filterField];
if(typeof field === 'number') {
query = query.replace(this.currency, '');
try {
Free download pdf