$emit doesn't trigger child events

♀尐吖头ヾ 提交于 2019-12-01 03:09:52

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')

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!