vue中的委托事件

Nil*_*ers 4 vue.js

我试图将一个事件从一个实例委托给另一个实例。

我在页面顶部有一个工具栏,其中有一个像这样的按钮

<div id="toolbar">
<button v-on:click="add" class="btn btn-default" type="submit"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Ny</button>
</div>
Run Code Online (Sandbox Code Playgroud)

此添加事件在此 vue 实例中工作

var toolbarApp = new Vue({
    el: '#toolbar',
    data: {

    },
    methods: {
        add: function (event) {
            alert('lol');
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

但现在我想将此添加事件附加到另一个实例,如下所示

var contactApp = new Vue({
    mixins: [toolbarApp],
    el: '#contact',
    data: {
        showGrid: true,
        showForm: false,
        editMode: false
    },
    created: function () {
        this.getContacts();
    },
    methods: {
        getContacts: function () {
            $.getJSON(this.apiGrid, function (data) {
                this.contacts = data;
            }.bind(this));
        },
        add: function (event) {
            alert('hej');
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

但由于实例不同,我无法附加此内容。有什么办法可以做到这一点吗?也尝试过使用 mixin 但没有运气。

谢谢指教

小智 5

你想做的事情并不独特,甚至有一个标题“事件总线”

\n\n
EventBus = new Vue();\n\nvar toolbarApp = new Vue({\n    el: \'#toolbar\',\n    data: {\n\n    },\n    methods: {\n        add: function (event) {\n            EventBus.$emit(\'add-something\', this.somevar);\n        }\n    }\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

然后在你的另一个实例中:

\n\n
var contactApp = new Vue({\n    mixins: [toolbarApp],\n    el: \'#contact\',\n    data: {\n        showGrid: true,\n        showForm: false,\n        editMode: false\n    },\n    created: function () {\n        this.getContacts();\n        EventBus.$on(\'add-something\', function(somevar) {\n            // do cool stuff, like this.getContacts...\n        });\n    },\n    methods: {\n        getContacts: function () {\n            $.getJSON(this.apiGrid, function (data) {\n                this.contacts = data;\n            }.bind(this));\n        },\n        add: function (event) {\n            alert(\'hej\');\n        }\n    }\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

定义:

\n\n

有时您需要一个快速简单的解决方案来在 Vue.js 组件之间传递数据。

\n\n

对于具有简单架构的应用程序来说,它足以使用事件在组件之间进行通信。为此,我们可以创建一个快速解决方案并实现 EventBus。EventBus 允许我们在一个组件中发出事件并在另一个组件中侦听该事件。

\n\n

https://medium.com/@andrejsabrickis/https-medium-com-andrejsabrickis-create-simple-eventbus-to-communicate- Between-vue-js-components-cdc11cd59860

\n