DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,503 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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>
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 (0)

This post blew up on DEV in 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!