通过子组件更新父数据

Updating parent data via child component?

本文关键字:数据 更新 组件      更新时间:2023-09-26

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

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

根据vue doc:

当父属性更新时,它将向下流向子属性,但是

子组件示例:

<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并不意味着将数据从子节点传递到父节点。数据绑定是单向的。

正确的过程是让子组件通过$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
});

你的父母可以这样听:

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

从上到下的单向绑定和事件机制的好处:

  • 你的父组件可以选择忽略事件,这样就可以让子组件在其他上下文中被重用。
  • 你的子组件(假设你有很多)将被允许只向上发送事件,这是更容易调试时,每个直接改变父状态。