我有一个带有计算属性的自定义对象...
class MyObject {
get someComputedProp() {
// expensive computation based on some other props
}
}
和一个包含约 500 个这些对象的 vuetify 数据表
<v-data-table
:headers="headers"
:items="myObjects"
:search="search"
>
<template slot="items" slot-scope="{ item }">
<td>{{ item.someComputedProp }}</td>
...
数据表加载速度很慢。通过实验,我发现我昂贵的 getter 在整个表中每个对象被调用了大约 4 次。如果我用返回字符串文字替换昂贵的 getter 的代码,我的表会很快。这带来了一些问题:
- 为什么 getter 每行被调用这么多次?
- 表格有分页,即使我的 getter 每行必须调用 4 次,为什么必须为每一行调用它,即使那些不在当前页上的行也是如此?
我可以让我的对象缓存昂贵的计算......
get someComputedProp() { if (!this._cachedComputedProp) this._cachedComputedProp = // expensive computation based on some other props } return this._cachedComputedProp }
这将使 4 次调用中的 3 次便宜,但在另一个 vue 上,我需要计算的 Prop 实时更新,因为它所依赖的 Prop 已更新。现在我被困在做这种愚蠢的事情......
set propThatComputedPropDependsOn (value) { this._cachedComputedProp = null this._propThatComputedPropDependsOn = value }
- 我该如何摆脱困境?
最佳答案
好吧,也许这对其他人有用:
- 我不明白为什么 getter 被调用了那么多次
- 我不明白为什么数据表会在 dom 中构建所有内容,甚至是用户可能永远不会翻页的内容
我修复了我的对象以(有时)缓存昂贵的计算。
// in constructor this.cacheProps = true get someComputedProp() { if (!this._cachedComputedProp || !this.cacheProps) this._cachedComputedProp = // expensive computation based on some other props } return this._cachedComputedProp }
在我的编辑器中,当我希望计算属性响应时,我将正在编辑的对象上的 cacheProps
设置为 false
。
关于javascript - Vuetify 数据表对于大量对象很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55555069/