Can I pass parameters in computed properties in Vue.Js

前端 未结 10 1224
借酒劲吻你
借酒劲吻你 2020-11-27 10:38

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 variab

10条回答
  •  执念已碎
    2020-11-27 10:45

    Most probably you want to use a method

    {{ fullName('Hi') }}
    
    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://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

提交回复
热议问题