[英]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.
当我更改输入字段中的文本时,它显示“初始属性 1”是 myprop1 的值,尽管我更改了输入。 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 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 HTML
<simple-input :myprop1="myprop1" :myprop2="myprop2"></simple-input>
<button @click="showMe">Show me!</button>
There's 2 main issues:有2个主要问题:
input
event for both inputs.input
事件。 You need to emit different events so that you can distinguish between them in the parent component. :myprop1="myprop1"
does nothing to the input element, there's no such myprop1
prop/attribute on inputs. :myprop1="myprop1"
对输入元素没有任何作用,输入上没有这样的myprop1
属性/属性。
myprop
is a terrible name, use value
instead. 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'], });
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.在您的父组件中,您需要监听
update:value1
和update:value2
事件,以便您可以从子组件接收新值。
<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.事实上,因为我们对事件使用了命名约定
update:prop
,所以我们可以使用sync
修饰符来进行 2-way 绑定。 So it becomes just:所以它变成了:
<!-- language: lang-vue -->
<simple-input
:value1.sync="value1"
:value2.sync="value2"
></simple-input>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.