vue.joedoe.dev

← Todas las recetasReactividad

Un computed que también se escribe

Con get y set, un v-model puede ir a un valor derivado y repartirlo entre los refs de verdad.

Demo.vue
<script setup lang="ts">
import { computed, ref } from "vue";

const first = ref("Joe");
const last = ref("Doe");

/* A computed with get and set: v-model writes the whole name, and the setter splits it. */
const full = computed({
	get: () => `${first.value} ${last.value}`.trim(),
	set(value: string) {
		const [head = "", ...rest] = value.split(" ");
		first.value = head;
		last.value = rest.join(" ");
	},
});
</script>

<template>
	<label>Nombre completo <input v-model="full" /></label>
	<p class="muted">
		Nombre: <code>{{ first }}</code> · Apellidos: <code>{{ last }}</code>
	</p>
	<label>O solo el nombre <input v-model="first" /></label>
</template>

Nombre: Joe · Apellidos: Doe

↑↓ moverse · ↵ abrir · esc cerrar