繁体   English   中英

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

[英]Vue.js delegate event handler to parent component?

我的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
        }
    },

    ...
});

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

子组件.vue

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

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

父组件.vue

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM