What is the directive v-model and how to use defineModel in a child component?
sobes.tech AI
Answer from AI
The v-model directive in Vue.js is used for two-way data binding between a parent and child component or between a form element and component data. It automatically binds the value and change event.
In Vue 3, to create a component supporting v-model in a child component, the defineModel function (in Composition API) or the model option in Options API is used. This allows specifying which property and event will be used for two-way binding.
Example of using defineModel in a child component:
<script setup>
import { defineModel } from 'vue'
defineModel('modelValue')
const props = defineProps({
modelValue: String
})
const emit = defineEmits(['update:modelValue'])
function updateValue(newValue) {
emit('update:modelValue', newValue)
}
</script>
<template>
<input :value="modelValue" @input="event => updateValue(event.target.value)" />
</template>
Thus, the parent component can use <ChildComponent v-model="someData" />, and the data will be synchronized.
If defineModel is not available, you can manually define the modelValue prop and the update:modelValue event to support v-model.