Home  >  Q&A  >  body text

Best practices for using getters and/or computed properties in Vue.js

I love vue.js and I definitely love computed properties and VueX getters. But I've reached a point where I'm not sure if the way I'm using them will have some performance disadvantages.

This is a common pattern in my code (also true for local component data and computed properties):

Start with this simple state (source of truth):

export default () => ({
   bonds: {
    eth: [],
    celo: []
  }
})

In my getter I usually do it the following way:

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....
  }
  ...
}

So, my question will be

  1. Is this considered a bad practice since I'm using a getter that depends on other getters? Are these considered circular dependencies?

  2. Should I always derive my getters directly from the source of truth? For example, change the above to...

getTotalBonds(state) {
    return state.bonds.eth.length + state.bonds.celo.length
}
  1. Is there a way to debug my getters or computed properties using the browser console to make sure I don't have performance issues or weird iteration loops etc?

Thank you very much if you take the time to answer!

P粉436688931P粉436688931201 days ago508

reply all(1)I'll reply

  • P粉946336138

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

    This will not be a circular dependency. A circular dependency will only occur when getter A depends on getter B, which in turn depends on getter A, which will lead to infinite recursion . The getters are OK, but as far as I know Vue calls them on every tick (for more information on what

    tick

    is, click here) , which is wasteful in most cases. Therefore, for values ​​that rarely change, it is recommended to use computed, because computed will only be called once, and Vue will cache the execution results.

    reply
    0
  • Cancelreply