Search code examples
vue.jsvuejs2v-modelvue-props

V-model and child components in VueJs


I have created a form component in VueJS and trying to bind the inputs to a parent component. I am not sure of the correct way to do this, and am confused that my current attempt works, as I don't think it should!

My parent component is:

<!-- parent component -->
<template>
  <div>
    <my-form :field="field" />
  </div>
</template>

<script>
export default {
  data: function() {
    return {
      field: {
        title: "title",
        options: "selectedOption"
      }
    }
 }
</script>

My child component is:

<!-- parent component -->
<template>
  <div>
     <input v-model="field.title" /> 
     <select v-model="field.selectedOption">
       <option>A</option>
       <option>B</option>
     </select>
  </div>
</template>

<script>
  export default {
    props: ["field"] 
  }
</script>

I was expecting that this would NOT work as I'm only binding the field value to my-form, but for some reason this seems to update the parent data field.

Could someone help me understand why this is working, and what the proper way of doing this is?

Vue version is 2.6.12.


Solution

  • Try to use v-model in parent component :

      <my-form v-model="field" />
    

    in child :

    
    <template>
      <div>
         <input :value="value.title" @input="$emit('input',{...value,title:$event.target.value})"/> 
         <select :value="value.selectedOption" @inpur="$emit('input',{...value,selectedOption:$event.target.value})">
           <option>A</option>
           <option>B</option>
         </select>
      </div>
    </template>
    
    <script>
      export default {
        props: ["value"] 
      }
    </script>