How do defineProps, defineEmits, and defineModel work in Vue 3 <script setup>?
❓ Interview Prompt: Explain compiler macros in script setup, TypeScript prop validation, custom event emission, and the Vue 3.4 defineModel() macro.
In '<script setup>', Vue provides compiler macros that do not need to be imported:
1. 'defineProps<T>()':
Declares props received from parent with full TypeScript type safety.
2. 'defineEmits<T>()':
Declares custom events the component can emit up to the parent ('emit("update", data)').
3. 'defineModel<T>()' (Vue 3.4+ Standard):
Previously, implementing two-way binding ('v-model') on a custom component required manually declaring a 'modelValue' prop and emitting an 'update:modelValue' event. 'defineModel()' replaces all of that boilerplate with a single macro returning a reactive ref bound to the parent's 'v-model'!
Code Implementation Example
<script setup lang="ts">
// 1. defineModel (Vue 3.4+) automatically binds to parent v-model!
const textValue = defineModel<string>({ required: true });
// 2. defineProps for component options
withDefaults(defineProps<{ label: string }>(), { label: 'Input' });
// 3. defineEmits for custom events
const emit = defineEmits<{ (e: 'focus'): void }>();
</script>
<template>
<label>{{ label }}</label>
<input v-model="textValue" @focus="emit('focus')" />
</template>Use defineModel() in Vue 3.4+ for two-way v-model binding instead of manual modelValue props and update emits.