V-model and child components in VueJs

1.3k Views Asked by At

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.

2

There are 2 best solutions below

1
On BEST ANSWER

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>
0
On

It seems the reason this works is because I'm passing an object, so the prop is referencing that object, and therefore I'm able to mutate the parent object directly in the child component.

As discussed here: https://forum.vuejs.org/t/v-model-on-prop/37639

As stated there, "It works but it’s not recommended. We want to keep one-way data flow.”

I'll therefore use the approach given by Boussandjra