BoumTAC
BoumTAC

Reputation: 3771

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?

Upvotes: 6

Views: 16346

Answers (2)

PaveeU
PaveeU

Reputation: 71

I just want to add something to the accepted answer: Do NOT use de-structured props inside computed functions. They won't detect the changes made to the values.

This works

const props = defineProps(['something'])
const computedValue = computed(() => {
  // This computed value will be re-calculated every time props.something changes
  return props.something + props.something
}

This doesn't

const { something } = defineProps(['something'])
const computedValue = computed(() => {
  // This computed value will only be calculated once and never again after
  return something + something
}

Upvotes: 7

TheAlexLichter
TheAlexLichter

Reputation: 7289

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>

Upvotes: 15

Related Questions