【问题标题】:Props don't update when input changes in component当组件中的输入更改时,道具不会更新
【发布时间】:2018-12-08 10:10:06
【问题描述】:

我有一个简单的组件,我尝试以两种方式绑定道具,但它只能以一种方式工作。当我更改输入字段中的文本时,它显示“初始属性 1”是 myprop1 的值,尽管我更改了输入。有什么问题?

我的组件

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']

});

ma​​in.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>

【问题讨论】:

  • 因为我不知道如果我有 2 个道具 - 每个输入一个道具

标签: javascript vue.js


【解决方案1】:

有两个主要问题:

  1. 您的子组件正在为两个输入发出 input 事件。您需要发出不同的事件,以便在父组件中区分它们。另外:

    • :myprop1="myprop1" 对输入元素没有任何作用,输入上没有这样的 myprop1 属性/属性。
    • myprop 是个糟糕的名字,请改用 value

    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'],
    });
    
  2. 在您的父组件中,您需要监听update:value1update:value2 事件,以便您可以从子组件接收新值。

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

    事实上,因为我们对事件使用了命名约定update:prop,所以我们可以使用sync 修饰符来进行双向绑定。所以它变成了:

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

【讨论】:

    猜你喜欢
    • 2018-08-09
    • 2018-07-02
    • 2020-06-17
    • 2020-01-19
    • 1970-01-01
    • 2016-09-23
    • 2019-03-03
    • 2021-06-15
    • 2021-11-03
    相关资源
    最近更新 更多