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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more