如何使用基于 props 的计算

Bou*_*TAC 2 computed-properties vue-props vuejs3 vue-composition-api

我尝试根据 props 值计算一个值,如下所示:

interface Props {
  task: Task;
}

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

然后在我的模板中,我显示计算值,totalPrice如下所示:{{ totalPrice }}。

我的计算从来不是计算,如果我在里面添加一个console.log,我永远不会输入它。

如何根据 props 计算值?

man*_*niL 13

下面是一个使用 Composition API 的示例 StackBlitz 实例<script setup>,不带. 如果您想使用<script setup>,请尝试:

<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>
Run Code Online (Sandbox Code Playgroud)


小智 5

我只想在已接受的答案中添加一些内容:不要在计算函数中使用解构的 props。他们不会检测到对值所做的更改。

这有效

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

这不

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