Vue.js将事件处理程序委托给父组件

Vue.js delegate event handler to parent component?

本文关键字:组件 程序 js 事件处理 Vue      更新时间:2023-09-26

我的VM上有一个全局组件,像这样

Vue.component('dropdown', function () {
    template: require('./templates/Dropdown.template.html'),
    components: {
        clients: require('./../modal/Clients.js')
    }
});

如您所见,此全局组件有自己的子组件 - clients

在这个子组件的模板中,我发生了click事件:

<button @click.prevent="submitForm"></button>

问题:

第一个全局组件Dropdown是否有可能负责处理此事件?

所以我会这样

Vue.component('dropdown', function () {
    ...
    methods: {
        submitForm: function () {
            // handling event
        }
    },
    ...
});

您可以在子组件中简单地执行此操作:

ChildComponent.vue

<button @click="$emit('click')">Child Component Button</button>

它将触发父级中定义的处理程序

ParentComponent.vue

<ChildComponent @click="myHandler()"/>

执行此操作的首选方法是使用 by 向上发送事件 $dispatch 这避免了紧密耦合,这稍微违背了独立、可重用组件的目的 文档中有一个非常相似的例子。