Member-only story

Understanding defineModel in Vue3

Shawn Kang
7 min readMar 8, 2024

--

Vue series of articles

With the release of vue3.4 version, defineModel has also officially become a regular version. It can simplify the two-way binding between parent and child components and is the currently officially recommended two-way binding implementation.

How to implement two-way binding in the past

Everyone should know that v-model is just syntactic sugar. It actually defines the modelValue attribute and listens for the update:modelValue event for the component, so we had to implement two-way data binding before. You need to define a modelValue attribute for the subcomponent, and when you want to update the modelValue value in the subcomponent, you need to emit send out a update:modelValue event. Pass the new value as the second field.

Let’s look at a simple example. The code of the parent component is as follows:

<template>
<CommonInput v-model="inputValue" />
</template>

<script setup lang="ts">
import { ref } from "vue";

const inputValue = ref();
</script>

--

--

Shawn Kang
Shawn Kang

Written by Shawn Kang

Focusing on front-end development and internet writing. Sharing technical tutorials and original fiction. https://skstory.online/

No responses yet

Write a response