官术网_书友最值得收藏!

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':
break;
case 'registered':
break;
}
return output;
}

We now just need to copy the code from our original formatting functions into the inpidual cases:

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

switch(key) {
case 'balance':
output = this.currency + field.toFixed(2);
break;

case 'registered':
let registered = new Date(field);
output = registered.toLocaleString('en-US');
break;
}
return output;
}

This format function is now a lot more flexible. We can add more switch cases should we need to cater for more fields (process the name field, for example) or we can add new cases to existing code. An example of this would be if our data contained a field that detailed the date on which the user deactivated their account, we could easily display it in the same format as registered:

      case 'registered':
case 'deactivated':
let registered = new Date(field);
output = registered.toLocaleString('en-US');
break;
主站蜘蛛池模板: 淮北市| 平泉县| 抚州市| 绥江县| 海口市| 濉溪县| 龙胜| 贡山| 嘉义市| 青川县| 京山县| 朔州市| 东宁县| 九台市| 丹寨县| 崇仁县| 大邑县| 阳江市| 高淳县| 确山县| 纳雍县| 台湾省| 玉环县| 余干县| 农安县| 东海县| 逊克县| 慈利县| 麦盖提县| 兴和县| 临湘市| 郧西县| 石狮市| 大洼县| 东山县| 武强县| 武功县| 岚皋县| 玉门市| 红原县| 唐河县|