Rob
Rob

Reputation: 637

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.

Upvotes: 0

Views: 1648

Answers (2)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

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>

Upvotes: 2

Rob
Rob

Reputation: 637

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

Upvotes: 1

Related Questions