💚 Vue.js Beginner

What is the defineProps and defineEmits in Vue 3 script setup?

Why Interviewers Ask This

Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid Vue.js basics — a prerequisite for any developer role.

Answer

In <script setup>, defineProps and defineEmits are compiler macros for declaring a component's props and custom events. They don't need to be imported. defineProps: // Runtime declaration: const props = defineProps({ title: String, count: { type: Number, required: true, default: 0 }, items: Array }); // TypeScript declaration (preferred): const props = defineProps<{ title: string; count?: number; items: string[]; }>(); // With defaults (TS): const props = withDefaults(defineProps<{ count?: number }>(), { count: 0 });. Access in template directly: {{ title }}. In script: props.count. defineEmits: // Runtime: const emit = defineEmits(["update:modelValue", "submit", "close"]); // TypeScript: const emit = defineEmits<{ "update:modelValue": [value: string]; submit: [data: FormData]; close: []; }>();. Usage: emit("update:modelValue", newValue);. defineModel() (Vue 3.4+): convenient macro for v-model: const model = defineModel<string>(); // access/set model.value. Creates the modelValue prop and update:modelValue emit automatically. With custom name: const visible = defineModel<boolean>("visible"). Type-only props validation: TypeScript declaration is safer and gives better IDE support than runtime declaration.

Pro Tip

This topic has Vue.js-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.