Reputation: 3159
<div @ontabselected="sayHelloFromRoot">
<tabs>
<tab></tab>
<tab></tab>
</tabs>
</div>
I am emitting the event ontabselected
from Tabs
component like this:
this.$emit('ontabselected', tab);
The sayHelloFromRoot
method resides in the root vue instance, consisting of only one line:
sayHelloFromRoot(){
console.log('hello');
}
But as soon as I switch between tab, in vue-devtools I see the event emitted, but in the console I don't see hello printed.
Upvotes: 0
Views: 97
Reputation: 1053
You should listen event on <tabs>
instead of <div>
, e.g.:
<div>
<tabs @ontabselected="sayHelloFromRoot">
<tab></tab>
<tab></tab>
</tabs>
</div>
It works the same way as any other event listener. Let's check an example:
<!-- MyFile.vue -->
<div>
<button @click="sayHello"/>
</div>
In general. the logic logic here is to listen for event on the component or element that emits the event. In this case, when you as a user click on the button, the click
event is fired on button (not on the wrapper div). And you actually listen for that even in upper component (MyFile.vue
) not inside the <button>
.
Even if we back to the roots and use just the html it works the similar way:
<div>
<button onclick="console.log('Hello')"/>
</div>
You don't know how button fires the event, it's encapsulated inside the button. But you know that it can emit that event, you know the interface and you can listen on it.
If the event was implemented in the root, it would be hard to know what button. (thanks @Ferrybig)
Upvotes: 1