- Vue.js 2.x by Example
- Mike Street
- 387字
- 2021-07-02 20:00:29
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;
- C++面向對象程序設計(第三版)
- 從零構建知識圖譜:技術、方法與案例
- Linux C/C++服務器開發實踐
- Java EE框架整合開發入門到實戰:Spring+Spring MVC+MyBatis(微課版)
- PyQt從入門到精通
- 實用防銹油配方與制備200例
- C語言程序設計案例式教程
- TypeScript實戰指南
- PySide GUI Application Development(Second Edition)
- HTML5入門經典
- Raspberry Pi Home Automation with Arduino(Second Edition)
- Scratch趣味編程:陪孩子像搭積木一樣學編程
- Processing創意編程指南
- 軟件體系結構
- Node.js從入門到精通