【问题标题】:Parent not listening to child $emit - VueJS父母不听孩子 $emit - VueJS
【发布时间】:2018-05-19 11:40:51
【问题描述】:

这是子组件:

Vue.component("training-edit", {
    template: "#training-edit-template",
    props: ["show"],
    data: function () {
        return {
            form: new Form(),
            isWorking: false
        }
    },
    watch: {
        show: function (val) {
            if (val) {
                $("#editTrainingModal").modal("show");
            } else {
                $("#editTrainingModal").modal("hide");
            }
        }
    },
    methods: {
        onCancel: function () {
            this.$emit("doneEditing");
        }
    }
});

这是父级:

new Vue({
    el: "#trainingEditContainer",
    data: {
        isWorking: false,
        showEditTraining: false
    },
    methods: {
        onEdit: function (e) {
            e.preventDefault();
            this.showEditTraining = true;
        },
        doneEditing: function () {
            this.showEditTraining = false; 
        }
    }
});

HTML:

<div id="trainingEditContainer" class="row">
    // unrelated stuff here

    <training-edit v-bind:show="showEditTraining"></training-edit>
</div>
<script id="training-edit-template" type="x-template">
    <modal-right modalId="editTrainingModal">
        <div class="modal-header">
            <button type="button" class="close" v-on:click="onCancel" aria-label="close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">Edit Training</h4>
        </div>
        @Html.Partial("Partial/_EditPartial")
    </modal-right>
</script>

我可以在 Chrome 的 Vue 开发人员工具中看到正在发出事件,但由于某种原因,父级没有听到它,并且永远不会调用 doneEditing 函数。我在这里遗漏了什么明显的东西吗?

【问题讨论】:

  • @Bert 父母没有模板,但孩子有,所以我将它添加到 OP。希望这有帮助吗?
  • 确实如此。你想watch 做什么?手表应该是一个对象。除此之外,这里的主要问题似乎是您从未为 doneEditing 事件设置侦听器。
  • @Bert 哎呀,我已经更正了watch 部分,这只是在这里发帖时的一个错字。我该如何收听活动?我以为父母一直在听,但我对Vue 还是比较陌生,所以我很容易出错。

标签: javascript vue.js vue-component


【解决方案1】:

首先,我建议您将活动名称更改为done-editing

this.$emit("done-editing")

这是因为 HTML 中的属性不区分大小写,如果您将某些模板渲染到 DOM,最好使用 avoid camelCased names。请注意,如果您在字符串中定义模板或使用单个文件组件,则这不适用。

那么你需要在组件上监听它。

<training-edit @done-editing="doneEditing" v-bind:show="showEditTraining">

当您从组件发出事件时,父级必须显式侦听该事件。

【讨论】:

  • 这正是我所缺少的。非常感谢您的帮助以及有关 HTML 和 camelCasing 的提示!
  • @Quiver 没问题 :)
猜你喜欢
  • 2020-01-22
  • 2019-11-21
  • 2020-06-26
  • 2021-10-16
  • 1970-01-01
  • 2017-08-26
  • 1970-01-01
  • 1970-01-01
  • 2021-02-23
相关资源
最近更新 更多