vue.joedoe.dev

← All the recipesComponentsVue 3.5+

Destructure props without losing reactivity

Since Vue 3.5 destructured props stay reactive and the defaults go right there. Goodbye 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)

↑↓ move · ↵ open · esc close