AngeloC
AngeloC

Reputation: 3523

How to use v-bind in a custom component?

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.

Upvotes: 7

Views: 5304

Answers (2)

Antoine Floury
Antoine Floury

Reputation: 1191

I get the same problem following the documentation :
https://v2.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>

Upvotes: 10

Amresh Venugopal
Amresh Venugopal

Reputation: 9549

You are emitting an input event inside an input event handler.

So the problem that happens here is:

  1. 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.

  2. 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.

Upvotes: 2

Related Questions