我喜欢vue.js,我肯定喜欢计算属性和VueX getters。但是我到了一个不确定的地步,不确定我使用它们的方式是否会在性能方面有一些缺点。
这是我代码中的一个常见模式(对于本地组件数据和计算属性也适用):
从这个简单的状态(真相源)开始:
export default () => ({
   bonds: {
    eth: [],
    celo: []
  }
})
在我的getter中,我通常会按照以下方式进行:
export default {
  getBondsEth(state) {
    return state.bonds.eth
  },
  getBondsCelo(state) {
    return state.bonds.celo
  },
  getTotalBondsEth(_, getters) {
    return getters.getBondsEth.length
  },
  getTotalBondsCelo(_, getters) {
    return getters.getBondsCelo.length
  },
  getTotalBonds(_, getters) {
    return getters.getTotalBondsEth + getters.getTotalBondsCelo
  },
  getWhateverComputationEth(_, getters) {
    return getters.getBondsEth.reduce... or map or filter or find etc....
  }
  ...
}
所以,我的问题将是
这是否被认为是一种不好的做法,因为我使用了依赖于其他getter的getter?这些被认为是循环依赖吗?
我是否应该总是直接从真相源派生我的getter?例如,将上述更改为...
getTotalBonds(state) {
    return state.bonds.eth.length + state.bonds.celo.length
}
如果您花时间回答,非常感谢!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这不会是一个循环依赖。只有当getter
A依赖于getterB,而getterB又依赖于getterA时,才会出现循环依赖,这将导致无限递归。getter是没问题的,但据我所知,Vue会在每个tick上调用它们(关于什么是tick的更多信息,请点击这里),这在大多数情况下是浪费的。因此,对于很少变化的值,建议使用
computed,因为computed只会被调用一次,Vue会缓存执行结果。