← Totes les receptes·ComponentsVue 3.5+
Desestructurar props sense perdre la reactivitat
Des de Vue 3.5 les props desestructurades continuen sent reactives i els valors per defecte van allà mateix. Adeu withDefaults().
Vue SFC
<script setup lang="ts">
import { computed, ref, watch } from "vue";
/*
* Vue 3.5: destructured props stay reactive and take plain default values,
* no withDefaults(). To watch one, wrap it in a getter.
*/
const { amount, currency = "EUR", locale = "es-ES" } = defineProps<{
amount: number;
currency?: string;
locale?: string;
}>();
const text = computed(() => new Intl.NumberFormat(locale, { style: "currency", currency }).format(amount));
const changes = ref(0);
watch(
() => amount,
() => changes.value++,
);
</script>
<template>
<output class="price">{{ text }}</output> <small>(cambios: {{ changes }})</small>
</template>
Vue SFC
<script setup lang="ts">
import { ref } from "vue";
import Price from "./Price.vue";
const amount = ref(24.9);
</script>
<template>
<label>Precio <input v-model.number="amount" type="number" step="0.1" /></label>
<ul>
<li><Price :amount="amount" /></li>
<li><Price :amount="amount" currency="USD" locale="en-US" /></li>
<li><Price :amount="amount" currency="JPY" locale="ja-JP" /></li>
</ul>
</template>