vue.joedoe.dev

← Totes les receptesReactivitat

Un computed que també s'escriu

Amb get i set, un v-model pot anar a un valor derivat i repartir-lo entre els refs de veritat.

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

↑↓ moure's · ↵ obrir · esc tancar