Can I pass parameters in computed properties in Vue.Js

ghz 8months ago ⋅ 76 views

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?

Answers

In Vue.js, computed properties are primarily used for deriving values based on other data properties in your component. Computed properties cannot accept arguments directly, as they are meant to be reactive and automatically update whenever their dependencies change.

If you need to compute a value based on dynamic input or parameters, you should indeed use methods instead of computed properties. Methods can accept parameters and return computed values based on those parameters.

Here's how you can achieve the desired functionality using methods instead of computed properties:

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

And then you can call this method in your template with the required parameter:

<div>{{ fullName('Hello') }}</div>

Using methods in this way allows you to compute values based on dynamic input, whereas computed properties are used for deriving values based on reactive data properties. If your computed value depends on other reactive data properties within your component, it's better to use computed properties. If you need to compute values based on dynamic input or parameters, methods are the way to go.