I wanted to ask, because it's still hard for me to understand what is the difference between
v-model and :model-value
In the documentation, I read that:
v-model is used on a native element:
<input v-model="searchText" />
but, when I use on a component, v-model instead expands to this:
<CustomInput
:modelValue="searchText"
@update:modelValue="newValue => searchText = newValue"
/>
And ok, I understand that. But sometimes I see, that in custom components we still using:
<CustomInput
v-model="searchText" // => why v-model, not :model-value
@update:modelValue="newValue => searchText = newValue"
/>
So I'm a confused a little bit, about why, and what is the difference between this two options.
Based on Vue.js documentation (link):
v-model can be used on a component to implement a two-way binding.
:prop is the shortcut for v-bind.
for example:
<BlogPost :title="post.title" /> is exactly the same as <BlogPost v-bind:title="post.title" />
on custom components v-model is just a shortcut for:
:modelValue="value"
@update:modelValue="newValue => value = newValue"
and on a native component v-model is just a shortcut for:
:modelValue="value"
@input="newValue => event => value = event.target.value"
(digitalocean on v-model)
as you see unlike v-bind, v-model allows for changing the value from inside the child component.
so if you use 'v-model' the line @update:modelValue="newValue => searchText = newValue" can be removed.
Please let me know if you have any questions.
In your exact case there is no difference, the same value just gets assigned twice.
This, hovewer, may make sence if the listener is not the same as just assignement:
<CustomInput
// same as
// :modelValue="searchText" @update:modelValue="v => searchText = v"
v-model="searchText"
// second listener for the same event
@update:modelValue="newValue => console.log('got', newValue)"
/>
playground
<script setup>
import { ref, watch } from 'vue'
import Comp from './Comp.vue'
const msg = ref('Hello World!\n')
const n = ref(123)
watch(n, () => { msg.value += `n has updated to ${n.value}\n` })
function update(v) {
msg.value += `update was called with ${v}\n`
}
</script>
<template>
<Comp v-model="n" type="number" @update:model-value="update" />
<br>
<textarea v-model="msg" rows=30 cols=70></textarea>
<!--
Hello World!
update was called with 124
n has updated to 124
update was called with 125
n has updated to 125
update was called with 126
n has updated to 126
update was called with 127
-->
</template>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With