Simplify Vue v-model with the New defineModel API in Vue 3.4
This article explains how Vue 3.4's defineModel feature eliminates the boilerplate required for custom v-model implementations, showing side‑by‑side examples of the old three‑line approach and the new single‑line declaration for reusable input components.
As a Vue developer you probably have a love‑hate relationship with the v-model directive. It offers powerful two‑way binding and is essential for reusable form components, but in <script setup> components creating a custom v-model always required several lines of boilerplate.
Recall the past: the v-model boilerplate we used to write
Before exploring the charm of defineModel, let’s review the cumbersome code we used to write.
Suppose we want to create a custom input component CustomInput.vue and allow the parent component to bind its value via v-model. In Vue 3.3 and earlier the code typically looks like this:
Parent component (App.vue)
<script setup>
import { ref } from 'vue'
import CustomInput from './CustomInput.vue'
const message = ref('Hello Vue')
</script>
<template>
<CustomInput v-model="message" />
<p>Current value: {{ message }}</p>
</template>Child component (CustomInput.vue) – old style
The child component required additional boilerplate to emit and accept the model value, which is omitted here for brevity.
The game‑changing defineModel
Now, with Vue 3.4’s defineModel, the same CustomInput.vue can be reduced to a single, intuitive declaration.
Child component (CustomInput.vue) – Vue 3.4+ style
<script setup>
// 1. Just this line, that’s it!
const model = defineModel()
</script>
<template>
<input v-model="model" />
</template>This represents a huge leap in developer experience: the three‑line boilerplate collapses into one clear statement, giving defineModel extreme simplicity and elegance.
JavaScript
Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
