Optimizing your App and Using Components to Display Data Chapter 3
Reducing the number of hard-coded variables
and properties, and reducing redundancy
When looking at the Vue JavaScript, it is quickly evident that it can be optimized by
introducing global variables and setting more local variables in the functions to make it
more readable. We can also use existing functionality to stop repeating ourselves.
The first optimization is in our filterRow() method where we check
whether filter.field is active. This is also repeated in the isActiveFilterSelected
method we use to show and hide our radio buttons. Update the if statement to use this
method instead, so the code is as follows:
...
if(this.filter.field === 'isActive') {
result = (typeof this.filter.query === 'boolean')?
(this.filter.query === person.isActive) : true;
} else {
...
The preceding code has the this.filter.field === 'isActive' code removed and
replaced with the isActiveFilterSelected() method. It should now look like this:
...
if(this.isActiveFilterSelected()) {
result = (typeof this.filter.query === 'boolean')?
(this.filter.query === person.isActive) : true;
} else {
...
While we're in the filterRow method, we can reduce the code by storing the query and
field as variables at the start of the method. result is also not the right keyword for this,
so let's change it to visible. First, create and store our two variables at the start and
rename result to visible:
filterRow(person) {
let visible = true,
field = this.filter.field,
query = this.filter.query;
...