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

As a compromise, we are going to pass the person object as the first parameter, so we can


access all the data, and the name of the field as the second parameter. We will then use this


for both identifying the format method required and to return the specific data.


Creating the method


In your view, replace both the formatDate and formatBalance functions with a singular


format one, passing in the person variable as the first parameter, and the field enclosed


quotes as the second:


<td v-bind:class="balanceClass(person)">
{{ format(person, 'balance') }}
</td>
<td>
{{ format(person, 'registered') }}
</td>

Create a new format method inside your Vue instance, which accepts two


parameters: person and key. As the first step, retrieve the field using the person object and


the key variable:


format(person, key) {
let field = person[key],
output = field.toString().trim();
return output;
}

We have also created a second variable inside the function titled output—this will be what


is returned at the end of the function and is set to the field by default. This ensures that if


our formatting key does not match the one passed in, the untouched field data is
returned—we do, however, convert the field to a string and trim any whitespace from the


variable. Running the app now will return the fields without any formatting.


Add a switch statement, setting the expression to be just the key. Add two cases to the


switch statement—one being balance and the other registered. As we do not wish for


anything to happen to our input when it does not match a case, there is no need for us to


have a default statement:


format(person, key) {
let field = person[key],
output = field.toString().trim();

switch(key) {
case 'balance':
Free download pdf