之前有写过一篇博客讲计算属性的学习,项目里有用到计算属性所以也就一起讲讲在ts里面怎么用,主要是避免改变一个其他不变的情况
get recordList() {
return store.recordList;
}
get groupedList() {
const {recordList} = this;
if (recordList.length === 0) {return [];}
const newList = clone(recordList)
.filter(r => r.type === this.type)
.sort((a, b) => dayjs(b.createdAt).valueOf() - dayjs(a.createdAt).valueOf());
type Result = { title: string; total?: number; items: RecordItem[] }[]
const result: Result = [{title: dayjs(newList[0].createdAt).format('YYYY-MM-DD'), items: [newList[0]]}];
for (let i = 1; i < newList.length; i++) {
const current = newList[i];
const last = result[result.length - 1];
if (dayjs(last.title).isSame(dayjs(current.createdAt), 'day')) {
last.items.push(current);
} else {
result.push({title: dayjs(newList[0].createdAt).format('YYYY-MM-DD'), items: [current]});
}
}
result.map(group => {
group.total = group.items.reduce((sum, item) => sum + item.amount, 0);
});
return result;
}
我在这里是有用到计算属性,而且在ts里面用法有些不同,直接get xxx就可以得到计算属性xxx了,它最主要的好处就是可以根据依赖缓存,从而节省内存,非常好用