【问题标题】:VueJS weird $emit behaviourVueJS 奇怪的 $emit 行为
【发布时间】:2021-11-30 01:07:11
【问题描述】:

我正在我的 Vue 应用程序中尝试一种非常奇怪的行为。

我的一个路由器视图中有以下两个组件:

<bootstrap-table @showcurrent-click="handleShowcurrent"
                 @edit-click="handleEdit" 
                 @delete-click="handleDelete"
                 @generated-id="retrieveID"
                 :columns="columns" 
                 :data="data" 
                 :options="options"></bootstrap-table>

<device-showcurrent :device="showCurrent" 
                    :show="showShowCurrentModal"
                    @modal-close="handleHideShowcurrentModal"></device-showcurrent>

问题

在我的device-showcurrent 组件中,这是一个引导模式,我使用 JQuery 处理 hide.bs.modal 事件并发出自定义 modal-close 事件,以便我可以处理来自路由器视图组件的事件(您可以在上一段代码@modal-close="handleHideShowcurrentModal") 是这样的:

mounted: function(){
        // Due to Javascript scope we assign this to a variable
        instance = this
        // This ID is generated on creation, and it works corretly.
        // I also checked that this JQuery event was triggering.
        $(`#${this.randomID}`).on('hide.bs.modal', e => {
            instance.$emit('modal-close')
        })
    }

但问题是事件不是来自device-modal,而是来自bootstrap-table(通过VueDevTools检查),所以我发布的第一段代码不起作用,但是以下是:

<bootstrap-table @showcurrent-click="handleShowcurrent"
                         @edit-click="handleEdit" 
                         @delete-click="handleDelete"
                         @generated-id="retrieveID"
                         @modal-close="handleHideShowcurrentModal"
                         :title="$t('message.audited_devices')" 
                         :columns="columns" 
                         :data="data" 
                         :options="options"></bootstrap-table>

        <device-showcurrent :device="showCurrent" 
                            :show="showShowCurrentModal"></device-showcurrent>

问题

这里发生了什么?自定义事件怎么可能是从另一个组件发出的?

非常感谢!

【问题讨论】:

  • 如果不能真正完整地分析它,这有点难以判断。我要检查的第一件事:instance 值是否引用了该表?而不是使用mounted: function() { ... },您可以尝试mounted() { ... },也许函数语法会混淆您的上下文。
  • 嗨@Frnak,感谢您的评论!我实际上找到了解决方案,我在下面发布了它。

标签: javascript jquery vue.js


【解决方案1】:

我发现了问题。我将mounted 挂钩更改为:

mounted: function() {
        let _this = this;
        $(`#${this.randomID}`).on('hide.bs.modal', function(e) {
            _this.$emit('modal-close')
        })
    }

这可能是范围问题。已通过以下方式解决:

  1. let声明“实例副本”(_this)。
  2. 将 JQuery 侦听器声明中的回调函数从箭头函数更改为普通函数。

仍然感觉很奇怪,因为事件正在发出,但这可能是因为我的bootstrap-table 组件上还有一个instance = this,它是全局范围的(Ì 也没有使用let)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 2015-07-20
    相关资源
    最近更新 更多