gpt4 book ai didi

javascript - 通过子组件更新父数据?

转载 作者:行者123 更新时间:2023-11-28 18:18:42 25 4
gpt4 key购买 nike

通过子组件更新父数据的正确步骤是什么?

在子组件中 - 我直接通过 props 修改父数据。我不确定这是否是错误的做法。

根据 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'] 直接修改数据到父组件

最佳答案

正如您所说,props 并不意味着将数据从子级传递到父级。数据绑定(bind)只是单向的。

正确的过程是子组件通过 $emit 向父组件发送事件以及一些值(可选)。

根据您的情况,您可以在子组件的 addLink 方法中执行以下操作:

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
});

您的 parent 可以按如下方式收听:

<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 来处理子组件的事件。在您的父组件中,您需要按如下方式定义此方法:

methods: {
// ... your other methods,
addUserLink: function(linkData) {
this.userData.links.push(linkData);
}
}

这种从上到下的单向绑定(bind)和事件机制的好处:

  • 如果需要,您的父组件可以选择忽略事件,从而使子组件可以在其他上下文中重用。
  • 您的子组件(假设您有很多)将只被允许向上发送事件,与每个子组件直接改变父状态相比,这更容易调试。

关于javascript - 通过子组件更新父数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40349648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com