Vue将事件处理程序传递给组件到另一个组件-事件“ updatefilters”的无效处理程序:未定义

时间:2019-01-18 11:46:01

标签: vue.js

我有一些嵌套组件。这是我的顶级组件,它位于页面HTML中:

<advanced-options-model ... @updatefilters="updateFilters"></advanced-options-model>

请注意如何将updateFilters传递到组件中。这是advanced-options-model组件及其相关的filter-checkboxes

var filterCheckBoxes = {
    template: `
    <div>
        <fieldset v-for="name in names">
            <legend v-text="name"></legend>
            <label v-for="...">
                <input type="checkbox" ... @change="$emit('updatefilters')">
                {{value}} ({{count}})
            </label>
        </fieldset>
    </div>
    `,
    props: ["updatefilters", ...]
};

var advancedOptionsModal = {
    components: {
        "filter-checkboxes": filterCheckBoxes
    },
    template: `
    <div class="modal" ...>
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                ...
                <div class="modal-body">
                    <filter-checkboxes ... @updatefilters="updatefilters"></filter-checkboxes>
                </div>
                ...
            </div>
        </div>
    </div>
    `,
    props: ["updatefilters", ...]
};

Vue.component('advanced-options-model', advancedOptionsModal);

实际上,如果我在advancedOptionsModal中删除了@updatefilters="updatefilters",则看不到任何错误,因此问题似乎出在此模板中。但是,在此模板中,我将此相同的函数传递给filter-checkboxes组件:

<filter-checkboxes ... @updatefilters="updatefilters"></filter-checkboxes>

这是我在检查器中看到的确切错误消息:

vue.js:616 [Vue warn]: Invalid handler for event "updatefilters": got undefined

found in

---> <FilterCheckboxes>
       <AdvancedOptionsModel>
         <Root>

1 个答案:

答案 0 :(得分:1)

首先,您没有 updateFilters传递到advanced-options-model组件中,而是将updateFilters方法绑定到updatefilters事件上。

要将参数绑定到组件,应使用v-bind:...或仅使用:...。简写@...用于v-on:...

如果您要将updatefilters组件中的filter-checkboxes事件“冒泡”到根组件,则应这样操作:

var filterCheckBoxes = {
    template: `
    <div>
        <fieldset v-for="name in names">
            <legend v-text="name"></legend>
            <label v-for="...">
                <input type="checkbox" ... @change="$emit('updatefilters')">
                {{value}} ({{count}})
            </label>
        </fieldset>
    </div>
    `
};

var advancedOptionsModal = {
    components: {
        "filter-checkboxes": filterCheckBoxes
    },
    template: `
    <div class="modal" ...>
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                ...
                <div class="modal-body">
                    <filter-checkboxes ... @updatefilters="$emit('updatefilters')"></filter-checkboxes>
                </div>
                ...
            </div>
        </div>
    </div>
    `
};

Vue.component('advanced-options-model', advancedOptionsModal);

还有其他地方:

<advanced-options-model ... @updatefilters="updateFilters"></advanced-options-model>
methods: {
  updateFilters() {
    // do something
  }
}