0
0
VueHow-ToBeginner · 3 min read

How to Use defineModel in Vue: Syntax and Example

In Vue, defineModel is used to declare a component's model property with its type and default value, enabling two-way binding with v-model. You use it inside the setup() function to define reactive props and emit events automatically.
📐

Syntax

The defineModel function takes three arguments: the property name as a string, the type of the property, and an options object where you can set a default value. It returns a reactive model binding that works with v-model.

  • Property Name: The name of the model prop, e.g., "modelValue".
  • Type: The expected data type, like String, Number, or Boolean.
  • Options: An object to set default values or other configurations.
js
const model = defineModel('modelValue', String, { default: '' })
💻

Example

This example shows a simple Vue component using defineModel to create a text input that binds its value with v-model. The model is reactive and updates the parent component automatically.

vue
import { defineComponent, defineModel } from 'vue'

export default defineComponent({
  setup() {
    const modelValue = defineModel('modelValue', String, { default: '' })
    return { modelValue }
  },
  template: `
    <input type="text" v-model="modelValue" placeholder="Type here" />
    <p>Current value: {{ modelValue }}</p>
  `
})
Output
An input box appears where typing updates the displayed text below in real time.
⚠️

Common Pitfalls

Common mistakes when using defineModel include:

  • Not matching the model property name with the v-model usage in the template.
  • Forgetting to return the model from setup(), so it is not reactive in the template.
  • Using incorrect types that do not match the expected prop type, causing warnings.

Always ensure the model name and type align with your component's usage.

js
/* Wrong: model name mismatch */
const modelValue = defineModel('value', String, { default: '' })
// But template uses v-model="modelValue"

/* Right: names match */
const modelValue = defineModel('modelValue', String, { default: '' })
📊

Quick Reference

ParameterDescription
Property NameName of the model prop, e.g., 'modelValue'
TypeData type like String, Number, Boolean
OptionsObject with default value and other settings

Key Takeaways

Use defineModel inside setup() to declare reactive model props for v-model binding.
Ensure the model property name matches the v-model usage in your template.
Specify the correct type and default value to avoid warnings and bugs.
Return the model from setup() so it is reactive and accessible in the template.