DEV Community

cn-2k
cn-2k

Posted on

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

Top comments (0)