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

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.

主站蜘蛛池模板: 墨江| 翼城县| 桑日县| 新邵县| 宁都县| 金秀| 苏州市| 聂荣县| 如皋市| 抚顺市| 高台县| 饶平县| 浦县| 盐边县| 茌平县| 凤庆县| 金坛市| 台南市| 遂宁市| 达拉特旗| 阿拉善左旗| 通河县| 九寨沟县| 广饶县| 江口县| 酒泉市| 上杭县| 阿勒泰市| 屏山县| 沙坪坝区| 湘阴县| 昌宁县| 驻马店市| 佛冈县| 奉化市| 浪卡子县| 五原县| 通山县| 南郑县| 新民市| 台北市|