vue.joedoe.dev

← Todas las recetasComponentesVue 3.5+

Desestructurar props sin perder la reactividad

Desde Vue 3.5 las props desestructuradas siguen siendo reactivas y los valores por defecto van ahí mismo. Adiós 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>
  • 24,90 € (cambios: 0)
  • $24.90 (cambios: 0)
  • ¥25 (cambios: 0)

↑↓ moverse · ↵ abrir · esc cerrar