[Vuejs]-Props don't update when input changes in component

0👍

There’s 2 main issues:

  1. Your child component is emitting the input event for both inputs. You need to emit different events so that you can distinguish between them in the parent component. Also:
  • :myprop1="myprop1" does nothing to the input element, there’s no such myprop1 prop/attribute on inputs.

  • myprop is a terrible name, use value instead.

    Vue.component('simple-input', {
      template: `
        <div>
          <input type="text" :value="value1" @input="$emit('update:value1', $event.target.value)">
          <input type="text" :value="value2" @input="$emit('update:value2', $event.target.value)">
        </div>
      `,
      props: ['value1', 'value2'],
    });
    
  1. In your parent component, you need to listen to the update:value1 and update:value2 events so that you can receive the new values from the child.

     <simple-input
       :value1="value1"
       :value2="value2"
       @update:value1="value1 = $event"
       @update:value2="value2 = $event"
     ></simple-input>
    

In fact, because we used the naming convention update:prop for the event, we can use the sync modifier to make the binding 2-way. So it becomes just:

<!-- language: lang-vue -->

    <simple-input
      :value1.sync="value1"
      :value2.sync="value2"
    ></simple-input>

Leave a comment