Vue.js & Composition API (50 Qs)•Part 3: Advanced Internals, Scale & Production Architecture (Senior / Lead)
Vue 3 `defineModel` Macro (Vue 3.4+): Two-Way State Binding.
senior LevelCode ExampleSystem DesignVue & Nuxt
In Simple Words:
defineModel eliminates boilerplate prop/emit pairings for v-model. Previously, two-way binding required declaring defineProps(['modelValue']) and defineEmits(['update:modelValue']). With defineModel, the compiler automatically handles the prop declaration and event emission as a synchronous ref.
vue
<!-- Child.vue with defineModel (Vue 3.4+) -->
<script setup lang="ts">
// Declares 'modelValue' prop and 'update:modelValue' emit automatically
const count = defineModel<number>({ default: 0 });
// Multiple models are supported with custom names:
const title = defineModel<string>('title', { required: true });
</script>
<template>
<button @click="count++">Count is {{ count }}</button>
<input v-model="title" />
</template>