書名: Vue.js 2.x by Example作者名: Mike Street本章字數: 297字更新時間: 2021-07-02 20:00:29
Optimizing the code
As we wrote the code while we were figuring out the problem, there comes a point when you need to take a step back and look at your code to optimize it. This could include reducing the number of variables and methods or creating methods, to reduce repeating functionality. Our current Vue app looks like the following:
const app = new Vue({
el: '#app',
data: { people: [...],
currency: '$',
filterField: '', filterQuery: '', filterUserState: '' }, methods: { activeStatus(person) { return (person.isActive) ? 'Active' :
'Inactive'; },
activeClass(person) { return person.isActive ? 'active' :
'inactive'; },
balanceClass(person) { let balanceLevel = 'success'; if(person.balance < 2000) { balanceLevel = 'error'; } else if (person.balance < 3000) { balanceLevel = 'warning'; } let increasing = false, balance = person.balance / 1000; if(Math.round(balance) ==
Math.ceil(balance)) { increasing = 'increasing'; } return [balanceLevel, increasing]; },
formatBalance(balance) { return this.currency + balance.toFixed(2); },
formatDate(date) { let registered = new Date(date); return registered.toLocaleString('en-US'); },
filterRow(person) { let result = true; if(this.filterField) { if(this.filterField === 'isActive') { result = (typeof this.filterUserState
=== 'boolean') ? (this.filterUserState
=== person.isActive) : true; } else { let query = this.filterQuery, field = person[this.filterField];
if(typeof field === 'number') { query.replace(this.currency, '');
try { result = eval(field + query); } catch(e) {}
} else { field = field.toLowerCase(); result =
field.includes(query.toLowerCase()); }
} } return result; },
isActiveFilterSelected() { return (this.filterField === 'isActive'); }
} });
Looking at the preceding code, there are some improvements we can make. These include:
- Reducing the number of filter variables and grouping logically
- Combining the format functions
- Reducing the number of hard-coded variables and properties
- Re-ordering methods into a more logical order
We'll cover these points inpidually so we have a clean code base for building components with.
推薦閱讀
- Getting started with Google Guava
- Python從菜鳥到高手(第2版)
- 編寫整潔的Python代碼(第2版)
- Python 3破冰人工智能:從入門到實戰
- STM32F0實戰:基于HAL庫開發
- JavaScript+Vue+React全程實例
- Teaching with Google Classroom
- 機器學習與R語言實戰
- Visual Basic程序設計上機實驗教程
- PHP+Ajax+jQuery網站開發項目式教程
- ExtJS Web應用程序開發指南第2版
- 視窗軟件設計和開發自動化:可視化D++語言
- Python Automation Cookbook
- JBoss AS 7 Development
- 系統分析師UML用例實戰