DEV Community

cn-2k
cn-2k

Posted on

2

New way of work with V-Model in Vue.js 3!

Vue.js 3.4 release introduces the new defineModel() macro, which is now stable! With it you can create v-model without writing props and emits for each one.

Previous way (Vue.js 3.3-):

<script setup>
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
</script>

<template>
  <input
    :value="props.modelValue"
    @input="emit('update:modelValue', $event.target.value)"
  />
</template>
Enter fullscreen mode Exit fullscreen mode

New Way (Vue.js 3.4+):

<script setup>
const model = defineModel()
</script>

<template>
  <input v-model="model" />
</template>
Enter fullscreen mode Exit fullscreen mode

Very clean, right?

You can also type your v-model:

const model = defineModel<string>()
Enter fullscreen mode Exit fullscreen mode

Points to note:

  • The value returned by defineModel() is a ref so you can access and mutate the value.
  • Keep in mind that defineModel() is a macro, so under the hood, everything is the same as in the previous version.

Make sure to read the Vue 3 docs for more info about the defineModel() usage:

https://vuejs.org/api/sfc-script-setup.html#definemodel
https://vuejs.org/guide/components/v-model#basic-usage

👋 While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay