Search code examples
vue.jsvue-componentevent-bus

Vue Eventbus: handler.apply is not a function


I want to reload one of my components when an other component changes (for example I send a put with axios)

I tried it with eventbus but I got this error:

handler.apply is not a function

In the component where I want to trigger:

EventBus.$emit('compose-reload', Math.random()*100);

Where I want to be triggered:

<template>
    <div class="">

        <div class="">
            <div class="columns">
                <div class="column is-one-fifth">
                    <div class="box">
                        <Menu></Menu>
                    </div>
                </div>
                <div class="column is-four-fifth">
                    <div class="box">
                        <router-view :key="key"></router-view>
                    </div>
                </div>
            </div>

        </div>
    </div>
</template>
<script>
    import Menu from './includes/Menu'

    import EventBus from '../../../event-bus';

    export default {

        components: {
            Menu,
        },
        data() {
            return {
                key: null
            }
        },
        mounted(){
            EventBus.$on('compose-reload', this.key);
        },
        created(){
            this.key = Math.random()*100
        }
    }
</script>

Solution

  • EventBus.$on expects a handler function as a second argument but the variable this.key is passed in, hence the error.

    You should change this :

    mounted(){
       EventBus.$on('compose-reload', this.key);
    }
    

    To this :

    mounted(){
       EventBus.$on('compose-reload', key => {
         this.key = key;
       });
    }