[Vuejs]-V-model and child components in VueJs

2👍

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>

1👍

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

👤Rob

Leave a comment