首頁  >  問答  >  主體

Vue.js中使用getter和/或計算屬性的最佳實踐

我喜歡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....
  }
  ...
}

所以,我的問題將是

  1. 這是否被認為是一種不好的做法,因為我使用了依賴其他getter的getter?這些被認為是循環依賴嗎?

  2. 我是否應該總是直接從真相來源衍生出我的getter?例如,將上述更改為...

getTotalBonds(state) {
    return state.bonds.eth.length + state.bonds.celo.length
}
  1. 是否有一種方法可以使用瀏覽器控制台來調試我的getter或計算屬性,以確保我沒有效能問題或奇怪的迭代循環等?

如果您花時間回答,非常感謝!

P粉436688931P粉436688931201 天前510

全部回覆(1)我來回復

  • P粉946336138

    P粉9463361382024-04-02 13:51:55

    這不會是一個循環依賴。只有當getter A 依賴getter B,而getter B 又依賴getter A 時,才會出現循環依賴,這將導致無限遞歸。

    getter是沒問題的,但據我所知,Vue會在每個tick上調用它們(關於什麼是tick的更多信息,請點擊這裡) ,這在大多數情況下是浪費的。因此,對於很少變化的值,建議使用computed,因為computed只會被呼叫一次,Vue會快取執行結果。

    回覆
    0
  • 取消回覆