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

(singke) #1
Optimizing your App and Using Components to Display Data Chapter 3

To access the data, update any references of filterField to this.filter.field. Note


the extra dot, denoting it is a key of the filter object. Don't forget to update filterQuery


and filterUserState references as well. For example, the


isActiveFilterSelected method would become:


isActiveFilterSelected() {
return (this.filter.field === 'isActive');
}

You will also need to update the v-model and v-show attributes in your view—there are


five occurrences of the various variables.


While updating the filtering variables, we can take this opportunity to remove one. With
our current filtering, we can only have one filter active at a time. This means the


query and userState variables are only being used at any one time, which gives us the


opportunity to combine these two variables. To do so, we'll need to update the view and


application code to cater for this.


Remove the userState variable from your filter data object and update any occurrence of


filter.userState in your view to filter.query. Now do a find and replace in your Vue


JavaScript code for filter.userState, again replacing it with filter.query.


Viewing your app in the browser, it will appear to initially work, being able to filter users


by the field. However, if you filter by status, then switch to any other field, the query field
won't show. This is because using the radio buttons sets the value to a Boolean which,


when trying to convert to lowercase for the query field, fails to do so. To tackle this, we can


convert whatever value is in the filter.query variable to a string using the native


JavaScript String() function. This ensures that our filtering function can work with any


filtering input:


if(this.filter.field === 'isActive') {
result = (typeof this.filter.query ===
'boolean')? (this.filter.query ===
person.isActive) : true;
} else {
let query = String(this.filter.query),
field = person[this.filter.field];
if(typeof field === 'number') {
query.replace(this.currency, '');
try {
result = eval(field + query);
} catch(e) {}
} else {
Free download pdf