QA
Intermediate LevelVue JS

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

html
<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>
💡Vue 3.4 defineModel macro simplifying two-way v-model binding.
🎯 Interview Key Takeaway

Use defineModel() in Vue 3.4+ for two-way v-model binding instead of manual modelValue props and update emits.

#defineProps#defineEmits#defineModel#Intermediate
Back to all Vue JS Questions→

More Vue JS Interview Questions

Beginner LevelVue JS

What is the difference between Options API and Composition API in Vue 3?

Beginner LevelVue JS

What is the difference between ref() and reactive() in Vue 3?

Beginner LevelVue JS

What is the difference between computed properties, methods, and watch/watchEffect?