【问题标题】:Event not fired when trying to fire event from a component to his grandparent尝试从组件向其祖父母触发事件时未触发事件
【发布时间】:2020-04-15 06:48:12
【问题描述】:

我正在尝试向组件的祖父母发出一个事件,为此我想从孙子向他的父母发出一个事件,然后向他的父母发出另一个事件。

但是,当我从大子组件发射时,我不断收到此错误,但不知道为什么。

TypeError: 无法读取未定义的属性“$emit”

我这里有三个组成部分(从祖父母到他的孙子):

祖父母:“编辑”

家长:“菜单”

孩子:“modal-new-item”

大子组件(modal-new-item)在发出这样的 axios 发布请求后发出一个事件:

axios
                    .post('/menusV2/newItem', {
                    orderId: this.order.orderId,
                    type: this.newType,
                    itemId: this.newItem.value,
                    meal: this.newMeal,
                    category: this.newCategory,
                    noOfServing: this.newNoOfServing
                    })
                    .then(function(){
                            this.$emit('newItem');
                            this.onReset();
                    })
                    .catch(function (error) {
                        console.log(error);
                    });

孙组件的父级(菜单)接收事件并发出另一个事件,如下所示:

Modal-new-item 是大子组件,他的父级(菜单)接收这样的事件:

<modal-new-item :order="order" :show="showModal" @newItem="newItem"></modal-new-item>

并像这样将事件发送到他的父组件(编辑):

    newItem(){
        this.showModal = false;
        this.$emit('newItem');
    },

祖父组件(编辑)从前一个组件(菜单)接收事件,如下所示:

            <Menu @newItem="refreshMenu"  @itemDeleted="refreshMenu" :order="menu" :menuItems="items" :specifications="specifications" :nutritionalValues="nutritionalValues"></Menu>

我做错了什么?我不明白大子组件在控制台中抛出的错误。

感谢您的帮助!

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    这是你声明函数的方式。

    当你使用 ES5 时,this 指的是函数。你要引用组件,所以需要不同的绑定。

    function () {} -> this 指的是这个函数的作用域。 () =&gt; {} -> this 被保留,引用组件。

    改变这个:

    .then(function(){
                     this.$emit('newItem');
                     this.onReset();
                   })
    

    到这里:

    .then(() => {
                 this.$emit('newItem');
                 this.onReset();
                })
    

    更多阅读:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

    为了更清楚一点,抛出错误是因为它期望函数范围具有 $emit 属性。通过保留 this 绑定,它将检查组件是否具有 $emit 属性。

    【讨论】:

      猜你喜欢
      • 2018-06-06
      • 1970-01-01
      • 2018-10-27
      • 2019-06-20
      • 2019-05-04
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      • 2021-02-05
      相关资源
      最近更新 更多