vuejs3vue-composition-apicomputed-propertiesvue-props

How to use computed based on props


I try to compute a value based on a props value like this:

interface Props {
  task: Task;
}

const totalPrice = computed(() => {
  return task.paymentDetail.products
    .map(p => p.amount)
    .reduce((partialSum, acc) => partialSum + acc, 0);
})

And then in my template I show the computed value totalPrice like this: {{ totalPrice }}.

My computed is never compute, if I add a console.log inside I never enter it.

How to compute a value based on a props?


Solution

  • Here is an examplary StackBlitz instance using the Composition API without <script setup>. If you want to use <script setup>, try:

    <script setup lang="ts">
    import { computed } from 'vue';
    
    interface Props {
      task: Task;
    }
    
    const props = defineProps<Props>()
    const totalPrice = computed(() => {
      return props.task.paymentDetail.products
        .map((p) => p.amount)
        .reduce((partialSum, acc) => partialSum + acc, 0);
    });
    </script>
    
    <template>
      {{ totalPrice }}
    </template>