For a VueJS 2.0 project I have the following on the parent component
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.
// Child:
created() {
this.$root.$on('popover', (e) => {
// Determine if popover should close, etc.
this.close()
})
},
// Parent:
this.$emit('popover', 'arg1', 'argn')
Remember to call $off in destroyed
as well.
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.
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.$refs.customInput.$emit('focus');
//or
this.$refs.customInput.directlyCallMethod();
This access the vue instance of the child and then you can emit an event that is heard by that component.
As par the documentation:
In Vue.js, the parent-child component relationship can be summarized as props down, events up. The parent passes data down to the child via props, and the child sends messages to the parent via events. Let’s see how they work next.
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.
You can use a custom Vue instance for that.
// Globally
const eventBus = new Vue()
// In your child
eventBus.$on('eventName', () => {
// Do something
});
// In your parent
eventBus.$emit('eventName')