According to the doc,
<input v-model="something">
is the same as:
<input
v-bind:value="something"
v-on:input="something = $event.target.value">
so I tried following and it works:
<input v-model='sample'>
<input v-bind:value='sample' v-on:input="sample = $event.target.value" >
now when I tried the same in a custom component, it triggers an error:
VM99:2Uncaught TypeError: Cannot read property 'value' of undefined
jsFiddle here
What am I missing here to make it work ? Thanks.
I get the same problem following the documentation :
https://vuejs.org/v2/guide/components.html#Using-v-model-on-Components
You can get the value directly by $event
instead of $event.target.value
This is the example of documentation with working code :
Vue.component('custom-input', {
props: ['value'],
template: `
<input
:value="value"
@input="$emit('input', $event)"
>
`
})
Now v-model
should work perfectly with this component:
<custom-input v-model="searchText"></custom-input>
You are emitting an input
event inside an input
event handler.
So the problem that happens here is:
First input
when you type in the <input>
input: function(event) {
self.$emit("input", event.target.value) // 2
}
You emit the value input to the target element.
Second emit is caused by the handler itself,
input: function(event) {
/* the value of event is no longer a DOM el
instead it is a string value which doesn't have a target property
it throws an error on the console. */
self.$emit("input", event.target.value)
}
Uncaught TypeError: Cannot read property 'value' of undefined
Here is the working fiddle.
EDIT
Also, in your component HTML, you are expecting $event
to have a target
which further should have a value
property.
self.$emit("input", event.target.value)
Here you are emitting a value therefore, it wouldn't work.
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