【问题标题】:Cannot dispatch function from component to parent Vue无法将功能从组件分派到父 Vue
【发布时间】:2016-01-27 23:51:47
【问题描述】:

我有一个简单的 Vue 演示,当用户单击按钮时会显示一个模式:

http://plnkr.co/edit/lZPD7HOjKFsNVNmnWAOB?p=preview

问题是,我也在尝试使用一个插件来生成一个可以进入模态的二维码,所以我在我的组件中设置了一个方法,它使用$dispatch 来调用一个名为@987654323 的函数@:

    methods: {
                showQR: function(){
                     console.log("Dispatching event for QR code")
                     this.$dispatch('showQR');
                     return this.showModal = true    
            }
     }

我的父 Vue 对象中的函数如下所示:

new Vue({
        el: 'body',
        events: {
            showQR: function(){
                console.log("Inside the parent Vue")
                new QRCode(document.getElementById("qrcode"), "http://stackoverflow.com/");
            }
        }
    });

我确实从组件中收到了消息 "Dispatching event for QR code",但父 Vue 上的功能不起作用。如果我将逻辑放在模板中,我可以显示 QR 码,但我宁愿避免这种情况。关于如何使$dispatch 工作的任何建议?我的目标是正确的 Vue 吗?顺便说一句,使用 VueRouter。任何帮助都会很棒!

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    看起来你的主应用逻辑被这个覆盖了:

    var App = Vue.extend({
        template: '<router-view></router-view>'
    })
    

    如果你将你的主要方法对象与这个扩展结合起来,你应该没问题。所以,这样的事情会起作用:

    var App = Vue.extend({
        el: 'body',
        events: {
            showQR: function(){
                console.log("Inside the parent Vue")
                new QRCode(document.getElementById("qrcode"), "http://stackoverflow.com/");
            }
        },
        template: '<router-view></router-view>'
    })
    

    你也很可能不想/不需要el: 'body',

    【讨论】:

      猜你喜欢
      • 2019-06-29
      • 1970-01-01
      • 2020-01-07
      • 1970-01-01
      • 2020-09-23
      • 2021-10-27
      • 2018-10-25
      • 2021-05-13
      • 1970-01-01
      相关资源
      最近更新 更多