[Vuejs]-Call a parent of parent function from child component

2👍

Child Component:

<template>
  <button @click="simpleMethod">smth</button>
</template>
<script>
...
methods: {
  simpleMethod() {
    this.$emit('callParentFunction'); // emit an event to parent
  }
}
</script>

ViewComponent:

<template>
  <onepage-layout>
    <child-component @callParentFunction="parentFunction"></child-component>
  </onepage-layout>
</template>
<script>
...
methods: {
  parentFunction() {
    console.log('I want to fire this function...')
  }
}
</script>

You can refer to my another answer.

The communication between parent and child should be using Props down events up, instead of directly call the function thru this.$parent.function(). You should $emit('callFunc') then @callFunc="function".

1👍

A good way to accomplish this is using a new vue instance as event bus :

window.EventBus = new Vue();

In your child component you can run childFunction:

 methods: {

        childFunction() {
            EventBus.$emit('call-parent-function')
        }

    }

Then in any component (like parent of parent!) you can listen to the event:

 created() {           

        EventBus.$on('call-parent-function', () => {
            this.parentFunction();
        })

    }

Leave a comment