javascriptvue.jsvuejs2

Can I pass parameters in computed properties in Vue.Js


is this possible to pass parameter in computed properties in Vue.Js. I can see when having getters/setter using computed, they can take a parameter and assign it to a variable. like here from documentation:

computed: {
  fullName: {
    // getter
    get: function () {
      return this.firstName + ' ' + this.lastName
    },
    // setter
    set: function (newValue) {
      var names = newValue.split(' ')
  
      this.firstName = names[0]
      this.lastName = names[names.length - 1]
    }
  }
}

Is this also possible:

computed: {
  fullName: function (salut) {
    return salut + ' ' + this.firstName + ' ' + this.lastName    
  }
}

Where computed property takes an argument and returns the desired output. However, when I try this, I am getting this error:

vue.common.js:2250 Uncaught TypeError: fullName is not a function(…)

Should I be using methods for such cases?


Solution

  • Most probably you want to use a method

    <span>{{ fullName('Hi') }}</span>
    
    methods: {
      fullName(salut) {
          return `${salut} ${this.firstName} ${this.lastName}`
      }
    }
    

    Longer explanation

    Technically you can use a computed property with a parameter like this:

    computed: {
       fullName() {
          return salut => `${salut} ${this.firstName} ${this.lastName}`
       }
    }
    

    (Thanks Unirgy for the base code for this.)

    The difference between a computed property and a method is that computed properties are cached and change only when their dependencies change. A method will evaluate every time it's called.

    If you need parameters, there are usually no benefits of using a computed property function over a method in such a case. Though it allows you to have a parametrized getter function bound to the Vue instance, you lose caching so not really any gain there, in fact, you may break reactivity (AFAIU). You can read more about this in Vue documentation https://v2.vuejs.org/v2/guide/computed.html#Computed-Caching-vs-Methods

    The only useful situation is when you have to use a getter and need to have it parametrized. For instance, this situation happens in Vuex. In Vuex it's the only way to synchronously get parametrized result from the store (actions are async). Thus this approach is listed by official Vuex documentation for its getters https://vuex.vuejs.org/guide/getters.html#method-style-access