Vue.js Developer interview question · Most asked
How does v-model work on components, and what does defineModel do?
Summary
On a component, v-model is shorthand for passing a modelValue prop and listening for update:modelValue. defineModel() (stable since Vue 3.4) declares that pair in one line and returns a ref you can read and assign, which emits the update automatically.
Longer Answer
<!-- Child: QuantityInput.vue -->
<script setup>
const qty = defineModel({ type: Number, default: 1 });
</script>
<template><input type="number" v-model="qty" min="1" /></template>
<!-- Parent -->
<QuantityInput v-model="cart.qty" />
Components can have several named models (v-model:title, v-model:open) and custom modifiers (v-model.trim). Before 3.4 you wrote the prop, the emit and a computed getter/setter by hand. Vue 3 replaced Vue 2's value/input convention and .sync with this scheme.
Key Points
- modelValue prop + update:modelValue event.
- defineModel (3.4+) simplifies it.
- Multiple named v-models.
- Replaces Vue 2's value/input and .sync.
More most-asked Vue.js Developer questions
- Options API or Composition API: what is the difference, and which would you use?
- How do props work, and what is one-way data flow?
- How does Vue 3's reactivity system work, and how does it differ from Vue 2's?
- computed, watch or watchEffect: when do you use each?
- ref or reactive: what is the difference, and when do you use each?
- How do you use Vue Router: dynamic routes, nested routes and navigation guards?
- Why does v-for need a key, and why should it not be the index?
- What are composables, and why did they replace mixins?