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
This is where you’ve misunderstood. $emit is used for child => parent component communication. Dispatching an $emit event won’t send it out globally. It will only send the event up to it’s parent. If your click handler isn’t a child of the parent component you need a different strategy.
So you don't pass events to a child-component, you change the prop of a child. And then in your child-component you create a watcher for that props. This is the way to make a child-component react on things happening outside of it. This is a really simple button-component which can do 2 things.
You don't fire events to your child-components. Instead, you change the prop on a child-component and then use a watcher in that child-component to fire some logic. Before we start with this example, you have to understand the following concept:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With