Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$emit doesn't trigger child events

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

like image 366
KArneaud Avatar asked Nov 16 '16 16:11

KArneaud


People also ask

What is the use of $emit event?

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.

How do I Pass events to a child component?

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.

How do I fire events to my child components?

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:


1 Answers

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.

like image 97
qw3n Avatar answered Sep 28 '22 10:09

qw3n