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

← All Vue.js Developer questions