Open In App

How to Pass Parameters in Computed Properties in VueJS ?

In this article, we are going to learn how can we pass parameters in computed properties. The difference between a computed property and a method is that computed properties are cached, Methods are functions that can be called normal JS functions, but computed properties will be “re-calculated” anytime their dependency changes in the component.

Approach

Example: This example shows the implementation of the above-explained appraoch.






<template>
  <div>
    <p>Computed Property: {{ computedValue }}</p>
    <button @click="updateComputed(10)">
          Update Value
    </button>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      baseValue: 5,
    };
  },
  computed: {
    computedValue() {
      // You can't pass parameters
      // directly to computed properties,
      // but you can use a method that takes
      // parameters to calculate the value.
      return this.calculateValue(this.baseValue);
    },
  },
  methods: {
    calculateValue(value) {
      // Perform computation based
      // on the passed parameter
      return value * 2;
    },
    updateComputed(newValue) {
      // Update the base value triggering a
      // re-calculation of computed property
      this.baseValue = newValue;
    },
  },
};
</script>

Step to run the application:

npm install
npm run dev

Output:




Article Tags :