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

Switch statements are a great alternative to if statements if you are comparing the same


expression. You are also able to have several cases for one block of code and even include a


default if none of the previous cases was met. As an example of one in use, our format


method might look like:


format(variable) {
switch (typeof variable) {
case 'string':
// Formatting if the variable is a string
break;
case 'number':
// Number formatting
break;
default:
// Default formatting
break;
}
}

The important thing to note is the break; lines. These finish each switch case. If a break


was omitted, the code would carry on and execute the following case—which sometimes is


the desired effect.


Autodetecting the variable type and formatting is a great way of simplifying your code.


However, for our app, it is not a suitable solution as we are formatting the date, which
when outputting the typeof results in a string, and would not be identifiable from other


strings we may wish to format.


Passing in a second variable

The alternative to the preceding autodetection is to pass the second variable into the
format function. This gives us greater flexibility and scalability should we wish to format


other fields. With the second variable, we can either pass in a fixed string that matches a
preselected list in our switch statement or we could pass in the field itself. An example of


the fixed string approach in the view would be:


{{ format(person.balance, 'currency') }}

This would work perfectly and would be great if we had several different fields that all


needed to be formatted like balance currently does, but there seems to be some slight


repetition in using the balance key and currency format.

Free download pdf