Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 422
AngeloC Avatar asked Mar 21 '17 04:03

AngeloC


2 Answers

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>
like image 151
Antoine Floury Avatar answered Oct 12 '22 02:10

Antoine Floury


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.

like image 27
Amresh Venugopal Avatar answered Oct 12 '22 01:10

Amresh Venugopal