Feralheart
Feralheart

Reputation: 1940

Vue: event-bus handler is undefined

I want to implement event-bus in my Vue app.

First I want to make event-bus calls to start loading. My main component's script tag where I call the $on look like this:

<script>
    import store from '../store.js'
    import EventBus from '../event-bus';

    import Header from './includes/Header'
    import Footer from './includes/Footer'
    import Loading from './includes/Loading'

    export default {
        data() {
            return {
                isLoading: null
            }
        },
        components: {
            Header,
            Footer,
            Loading
        },
        mounted() {
            EventBus.$on('isLoading'), function (payLoad) {
                console.log(payload)
                this.isLoading = payload
            };
        }
    }
</script>

But I got this error:

[Vue warn]: Error in event handler for "isLoading": "TypeError: handler is >undefined"

How can I fix it?

Upvotes: 1

Views: 3200

Answers (1)

skirtle
skirtle

Reputation: 29132

You've got two mistakes. It should look like this:

EventBus.$on('isLoading', (payLoad) => {
  console.log(payload)
  this.isLoading = payload
});

Mistake 1 is the closing ) before the comma, leading to $on being called without a function. This is what is causing the warning message. That closing ) should be at the end, between the } and the ;.

Mistake 2 is using a normal function, leading to this being incorrect inside the function. An arrow function will preserve the this value from the surrounding scope.

I suggest using an IDE or a linter that can pick up on these kinds of problems. Your code was syntactically valid but these kinds of mistakes can easily be detected by suitable tooling.

Upvotes: 3

Related Questions