Search code examples
vue.jsvuexcomputed-properties

Vue effectively using computed property


I have the below code in my computed property. The function is expected to get way complicated. Is it correct to have it all here? I would like to have it in my store file, but I'm not able to call a function by name from within the computed property. Any advice ?

computed: {
  assignValue() {
    this.valueToSet = this.value1;
    
    if (this.valueToSet < 10) {
      return "1 week"
    } else if (this.valueToSet < 20) {
      return "2 weeks"
    } else if (this.valueToSet < 30) {
      return "3 weeks"
    } else {
      return 0;
    }
  }
}

To summarize, I would like to have it in my store.js (vuex), but how can I call/trigger a function by name inside "the computer property".

If it is not possible, any effective alternative? Or I should continue this way?


Solution

  • Vuex itself has getter properties that you can use with Vue component's computed property as shown in the docs.

    As far as your code is concerned, there is no problem with your current approach. You should move this code to Vuex getter when you need to re-use that state in multiple components.

    The only problem in your code is this.valueToSet = this.value1;. Computed properties should not produce a side-effect (including assignment). There is no direct harm, but it can have unintended consequences internally as computed values are cached. If you still need this part - this.valueToSet = this.value1; - move it to other computed property or use watch expression.