- Vue.js 2.x by Example
- Mike Street
- 281字
- 2021-07-02 20:00:29
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.
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.
- 精通JavaScript+jQuery:100%動態(tài)網頁設計密碼
- C語言程序設計(第2 版)
- 人臉識別原理及算法:動態(tài)人臉識別系統(tǒng)研究
- Mastering Python Networking
- 一塊面包板玩轉Arduino編程
- Java高并發(fā)核心編程(卷1):NIO、Netty、Redis、ZooKeeper
- Instant PHP Web Scraping
- Image Processing with ImageJ
- 深入實踐Kotlin元編程
- JavaScript+jQuery網頁特效設計任務驅動教程
- Angular應用程序開發(fā)指南
- Python期貨量化交易實戰(zhàn)
- Python青少年趣味編程
- C#面向對象程序設計(第2版)
- 計算機應用基礎(第二版)