$emit doesn't trigger child events

2019-02-16 11:37发布

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

5条回答
贪生不怕死
2楼-- · 2019-02-16 12:07

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.

enter image description here

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.

查看更多
ら.Afraid
3楼-- · 2019-02-16 12:09

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.

查看更多
Rolldiameter
4楼-- · 2019-02-16 12:20

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')
查看更多
地球回转人心会变
5楼-- · 2019-02-16 12:31

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.

查看更多
成全新的幸福
6楼-- · 2019-02-16 12:31

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.

查看更多
登录 后发表回答