0
You should just need to change the template to:
<div class="container" id="app">
<tweet-postbox @add-tweet="addTweet"></tweet-postbox>
</div>
The @add-tweet
part registers an event listener for the add-tweet
event. I’ve used kebab case to avoid browser case-sensitivity problems. You’d need to emit the event with the same name, this.$emit('add-tweet', response)
. See the offical documentation to confirm that kebab case is the way to go.
The ="addTweet"
parts assigns the method addTweet
as the listener.
https://v2.vuejs.org/v2/guide/events.html#Method-Event-Handlers
0
Found this great answer on another post:
https://stackoverflow.com/a/47004242/2387934
Component 1:
<!-- language: lang-js -->
this.$root.$emit('eventing', data);
Component 2:
<!-- language: lang-js -->
mounted() {
this.$root.$on('eventing', data => {
console.log(data);
});
}
-1
First of all, please fix your coding style, there’s a lot of issues including indentation errors, try using eslint
maybe.
Second, let’s break this.$emit('addTweet')
down a bit:
this
is in that line refers to the instance of the Vue component, thus an instance ofTweetPostBox
.- When you call
$emit
with aaddTweet
, you’re dispatching an event within the component.
Now that addTweet
is dispatched, what’s going to happen next? Vue is going to find all event handlers that handle addTweet
and executes them.
Now in your case, you do not have any event handlers for this event. addTweet
in your parent component is simply a local function in that component, it is not an event listener by any means.
To register an event listener, Vue provides @
syntax, and you’re already using that with @click
, so just like you are doing @click="dosomething"
(thus registering an event handler for onClick
you need to use @add-tweet
. (@addTweet
also works but it is against coding style standards, Vue automatically handles the conversion for you)