在vue中委派活动

时间:2017-06-02 19:01:29

标签: vue.js

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

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

<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>

此vue实例中的此添加事件

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

    },
    methods: {
        add: function (event) {
            alert('lol');
        }
    }
});

但现在我想将此添加事件附加到另一个像这样的实例

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');
        }
    }
});

但由于实例不同,我无法附上这个。有没有办法做到这一点? 也尝试过没有运气的混合物。

感谢您的建议

1 个答案:

答案 0 :(得分:4)

你要做的事情并不是独一无二的,甚至还有它的标题&#34;事件总线&#34;

EventBus = new Vue();

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

    },
    methods: {
        add: function (event) {
            EventBus.$emit('add-something', this.somevar);
        }
    }
});

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

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

<强>定义:

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

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

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

相关问题