CodeSpent
CodeSpent

Reputation: 1904

Accepting args in $emit - Vue

A very simple alert implementation using $emit, but when passing arguments it behaves as if the event had never even occurred. On the event, I want to set the value of alert to the result.

I am listening on mount as:

this.$eventHub.$on('alert', data =>       
  this.alert = data
})

Will Work:

this.alert is undefined, but set.

this.$eventHub.$emit('alert')

Won't Work:

this.alert is never set & event is never heard.


this.$eventHub.$emit('alert', {'message':'Signal Test', 'color':'error'})

What is occurring here?

Upvotes: 1

Views: 83

Answers (2)

CodeSpent
CodeSpent

Reputation: 1904

Not necessarily an answer, but more a user error. The issue is that I was signalling the event in the same component that I was listening for it on. I used all the same code, just simply moved the listener to a different component.

This may be as designed, but I didn't get any output to make this clear in console so I'm unsure if this behavior is expected or a bug.

Welcome any answers that may offer some context on why this occurs!

Upvotes: 0

nook
nook

Reputation: 1884

You can use this.$emit from the vue component. Take this example:

<template>
    <myComponent @customEvent="myCallback($event)" />
</template>

And the script:

export default {
  methods: {
    myCallback(data) {
      console.log(data); // here you have your event data
    }
  }
}

And in your child component:

export default {
  methods: {
    onClick() {
      // this.$emit(eventname, data);
      this.$emit('customEvent', 'some data');
    }
  }
}

Upvotes: 1

Related Questions