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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

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

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay