通过子组件更新父数据? [英] Updating parent data via child component?
问题描述
通过子组件更新父数据的正确程序是什么?
What is correct procedure to update parent data via child component?
在子组件中 - 我通过 props
直接修改父数据.我不确定这是否是错误的做法.
In the child component - I am modifying parent data directly via props
. I am not sure if this is wrong way to go about it.
根据 vue 文档:
当父属性更新时,它会向下流向子属性,但是反之亦然.
when the parent property updates, it will flow down to the child, but not the other way around.
示例子组件:
<script>
export default {
props: ['user'],
data: function () {
return {
linkName: '',
linkValue: '',
}
},
methods: {
addLink: function (event) {
event.preventDefault();
this.$http.post('/user/link', {name: this.linkName, key: this.linkValue}).then(response => {
this.user.links.push(response.data);
}, response => {
// Error
}
});
},
}
}
</script>
我使用了 this.user.links.push(response.data);
它通过 props: ['user']
直接将数据修改到父组件
I have used this.user.links.push(response.data);
which modify the data directly to the parent component via props: ['user']
推荐答案
正如您所说,props
并不意味着将数据从子级传递到父级.数据绑定是单向的.
As you rightly said, the props
is not meant to pass data from child to parent. The data binding is one-way only.
正确的过程是子组件通过 $emit 向父组件发送一个事件,以及一些值(可选).
The correct procedure is for child component to send an event via $emit to the parent component, along with some value (optional).
在你的情况下,你可以在子组件的 addLink
方法中执行以下操作:
In your case, you may do the following in the addLink
method of child component:
this.$http.post('/user/link', {name: this.linkName, key: this.linkValue}).then(response => {
this.$emit("update-user-links", response.data); // Send an event to parent, with data
}, response => {
// Error
});
您的父母可以按以下方式收听:
And your parent can listen to it as follows:
<my-user-link-component :user="userData" v-on:update-user-links="addUserLink"></my-user-link-component>
或简写语法:
<my-user-link-component :user="userData" @update-user-links="addUserLink"></my-user-link-component>
在上面,您分配了一个方法 addUserLink
来处理子组件的事件.在你的父组件中,你需要这样定义这个方法:
In the above, you are assigning a method addUserLink
to handle the child component's event. In your parent component, you need to define this method as follows:
methods: {
// ... your other methods,
addUserLink: function(linkData) {
this.userData.links.push(linkData);
}
}
这种从上到下的单向绑定和事件机制的好处:
Benefits of this one-way binding from top to bottom and the event mechanism:
- 如果需要,您的父组件可以选择忽略事件 - 从而使子组件可在其他上下文中重用.
- 您的子组件(假设您有很多)将只允许向上发送事件,与直接改变父状态的每个组件相比,这更容易调试.
这篇关于通过子组件更新父数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!