DEV Community 👩‍💻👨‍💻

Caio Vinicius
Caio Vinicius

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>
  modelValue: String

let emit = defineEmits(['update:modelValue']);
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.

    @keyup="emit('update:modelValue', $"
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">
  modelValue: string,

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

    @input="emit('update:modelValue', ($ as HTMLInputElement).value)"
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.


References for this post:

Top comments (0)

Create an Account!

👀 Just want to lurk?

That's fine, you can still create an account and turn on features like 🌚 dark mode.