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

This attribute is firing the changeFilter method on every update and passing it the


$event data of the change. This default Vue event object contains a lot of information that


we could utilize, but the target.value data is the key we are after.


Create a new method in your Vue instance that accepts the event parameter and updates


both the query and field variables. The query variable needs to be cleared, so set it to an


empty string, whereas the field variable can be set to the value of the select box:


changeFilter(event) {
this.filter.query = '';
this.filter.field = event.target.value;
}

Viewing your application now should clear whatever the filter query is, while still


operating as expected.


Combining the format functions


Our next optimization will be to combine the formatBalance and formatDate methods


in our Vue instance. This would then allow us to scale our format functions without


bloating the code with several methods with similar functionality. There are two ways to
approach a format style function—we can either auto-detect the format of the input or pass


the desired format option in as a second option. Both have their pros and cons, but we'll
walk through both.


Autodetection formatting

Autodetection of the variable type, when passed into a function, is great for cleaner code. In
your view, you could invoke the function and pass the one parameter you wish to format.


For example:


{{ format(person.balance) }}

The method would then contain a switch statement and format the variable based on the


typeof value. A switch statement can evaluate a single expression and then execute


different code based on the output. Switch statements can be very powerful as they allow


clauses to be built up—utilizing several different bits of code based on the result. More can


be read about switch statements on MDN.

Free download pdf