【问题标题】:Vue calling parent component function when child component function completes子组件功能完成时Vue调用父组件功能
【发布时间】:2020-01-07 00:23:26
【问题描述】:

在 Vue 中,我有一个主组件,其中包含一个子组件,该子组件通过一个按钮加载到页面上,并且该按钮触发 saveTaskComment()。这非常有效,我可以进入子组件函数的.finally 部分。但是,当它完成并到达那一点时,我想回调父组件以再次调用方法getInformation。我现在的方式行不通,所以我猜 $parent 在这种情况下是不正确的。

我需要做什么才能让 childComponent 中的方法调用原始函数

主组件

methods: {
    getInformation() {
        this.$root.$emit('fetchCommentsEvent');
    },
}

子组件

saveTaskComment() {

/*function completes and gets to this step fine*/

    .finally(() => {
        this.$parent.getInformation();
    });
}

【问题讨论】:

  • 我不认为你可以。您应该将finally 中的事件发送回父级,并让父组件在发出某些事件时调用getInformation()
  • 我如何将事件发送回父级?

标签: javascript vue.js


【解决方案1】:

我在CodeSandbox 上做了一个示例来说明我在评论中所说的话。

这里要带走的关键点是,当您将 Child 的模板插入 Parent 的模板时,您想监听某个事件并在事件发出时调用 getInformation()

<Child @foo="getInformation()">This is child.</Child>

要将此foo 事件发送回父级,您只需在子组件中执行this.$emit(eventName, optionalData)

由于我们正在侦听 foo 事件,因此您希望像这样发出它。

this.$emit("foo");

【讨论】:

    【解决方案2】:

    要从子组件发出某些方法,您必须将该方法传递给子组件。

    MainComponent.vue:

    <child-comp @getInformation="getInformation" />
    

    ChildComponent.vue:

    .finally(() => {
        this.$emit('getInformation')
    });
    

    如果你想将一些数据传递给父方法,你可以这样做

    this.$emit('getInformation', dataVariable)
    

    【讨论】:

    • Vue's guidelines 表示始终使用 kebab 大小写的事件名称,例如 @get-information$emit('get-information')。使用驼峰式事件名称时可能会遇到区分大小写的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 2017-07-22
    • 1970-01-01
    相关资源
    最近更新 更多