简体   繁体   中英

Props don't update when input changes in component

I have this simple component where I try to bind props both ways but it only works one way. When I change the text in my input fields, it shows 'Initial property 1' to be the value of myprop1 although I changed the input. What could be wrong?

My component

Vue.component('simple-input', {

    template: `
        <div>
            <input type="text" :myprop1="myprop1" :value="myprop1" @input="$emit('input', $event.target.value)">
            <input type="text" :myprop2="myprop2" :value="myprop2" @input="$emit('input', $event.target.value)">
        </div>
    `,

    props: ['myprop1', 'myprop2']

});

main.js

new Vue({
    el: '#root',

    data: {
        myprop1: 'Initial property 1',
        myprop2: 'Initial property 2',
    },

    methods: {
        showMe()
        {
            alert('prop1 - ' + this.myprop1);
            alert('prop2 - ' + this.myprop2);

            this.myprop1 = 'new value';
            this.myprop2 = 'new value';
        }
    }
});

HTML

<simple-input :myprop1="myprop1" :myprop2="myprop2"></simple-input>

<button @click="showMe">Show me!</button>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM