For a VueJS 2.0 project I have the following on the parent component
<template>
<child></child>
<button @click="$emit('childEvent)"></button>
</template>
on the child component I have:
{
events: { 'childEvent' : function(){.... },
ready() { this.$on('childEvent',...) },
methods: { childEvent() {....} }
}
Nothing seems to work on button click. Is it that I need to create a parent method that would then emit to the child? I was using vuejs 1. but now I'm confused as to the ways parent to child communications work
As par the documentation:
So in latest Vue, you can not send events from parent to child, you can pass props to child, and send event from child to parent.
I needed to do this for a popover where several could exist and props for each one are inappropriate.
To dispatch global events it is possible to add event listeners to the $root Vue instance.
Remember to call $off in
destroyed
as well.You can use a custom Vue instance for that.
While the other answers are correct and it is usually possible to use a data driven approach.
I'm going to add this for anyone looking for an answer to this question who need a way other than props. I ran into a similar problem when trying to set focus on a particular input inside a custom form component. To do this I had to give the custom component a ref then do this.
This access the vue instance of the child and then you can emit an event that is heard by that component.
Events from parent to child are done with
$broadcast()
in Vue 1.0 and are not possible at all in Vue 2.0.And you possibly don't need that, there usually is a better solution than doesn't need events, but that depends on your usecase.