DEV Community

cn-2k
cn-2k

Posted on

Working with v-model in Vue 3

In this post I will show you'll how to work with v-model in Vue 3 + Composition API using <script setup> on custom components, there's few ways to work with it, let's take a look!

First of all we always need to create an custom prop and emit for parent component:

1 - Creating modelValue prop and update emit (child component)

<script setup>
defineProps({
  modelValue: String
});

let emit = defineEmits(['update:modelValue']);
</script>
Enter fullscreen mode Exit fullscreen mode

Note: 'update:modelValue' can't be changed on next steps, otherwise the emit event wont work.

2 - Firing the emit event (child component)

In this case I will use an textarea to do it, but you can use with an input too.

<template>
  <textarea
    @keyup="emit('update:modelValue', $event.target.value)"
    v-text="modelValue" 
  />
</template>
Enter fullscreen mode Exit fullscreen mode

3 - Using your custom component (parent component)

Now you can call your custom component and pass a v-model.

<MyFancyTextArea v-model="comment" />
Enter fullscreen mode Exit fullscreen mode

Usage with Typescript

For use v-model w/ Typescript is very simple, look the example below:

<script setup lang="ts">
defineProps<{
  modelValue: string,
}>()

const emit = defineEmits<{
    (event: 'update:modelValue', payload: string): void;
}>();
</script>

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

That's it!

If you want to read and learn more details about v-model usage, please make sure to visit the Vue 3 official documentation about it.

See'ya!


References for this post:
https://blog.q-bit.me/an-introduction-to-vue-3-typescript-component-properties-and-events/
https://vuejs.org/guide/components/events.html#usage-with-v-model

Top comments (1)

Collapse
 
wrongrook profile image
Tim

I think you might need to add :value="modelValue" in your typescript version.