1. vue - writable computed
2-way data
<!-- Parent.vue -->
<template>
<MyInput
:modelValue="msg"
@update:modelValue="msg = $event"
/>
</template>
Writable Computed
Parent.vue
<script setup lang="ts">
const msg = ref('');
</script>
<template>
<div>
<p>msg = {{ msg }}</p>
<MyInput v-model="msg" class="mt-8" />
</div>
</template>
MyInput.vue
<script setup lang="ts">
const props = defineProps<{
modelValue: string
}>()
const emit = defineEmits<{
(e: 'update:modelValue', value: string): void
}>()
const msg = computed({
get() {
return props.modelValue;
},
set(newValue) {
emit('update:modelValue', newValue);
}
})
</script>
<template>
<div>
<input
type="text"
v-model="msg"
/>
<div class="flex justify-end">
<button @click="msg = ''">Reset</button>
</div>
</div>
</template>
Writable Computed Composable hook
// oversimplified version of vueuse useVModel
export function useVModel (props, key, emit) {
return computed({
get: () => props[key],
set: (newValue) => emit(`update:${key}`, newValue)
})
}
<script setup lang="ts">
const props = defineProps<{
modelValue: string
}>()
const emit = defineEmits<{
(e: 'update:modelValue', value: string): void
}>()
const msg = useVModel(props, 'modelValue', emit)
</script>
<template>
<div>
<input type="text" v-model="msg" />
<div class="flex justify-end">
<button @click="msg = ''">Reset</button>
</div>
</div>
</template>