How to call methods in App.vue from Vue components?

To call methods defined in the App.vue component from child components, you can use Vue’s event bus, props, or Vuex, depending on your application’s complexity and requirements.

To do this we can do one of the following

1. Using Vue’s Event Bus:

In your App.vue, you define an event bus:

// App.vue
import Vue from 'vue';

export const eventBus = new Vue();

Then, in your child component, you emit an event to call a method in App.vue:

// ChildComponent.vue
<template>
  <button @click="callMethodInApp">Call Method in App.vue</button>
</template>

<script>
import { eventBus } from '@/App.vue';

export default {
  methods: {
    callMethodInApp() {
      eventBus.$emit('callMethod', /* pass any arguments if needed */);
    }
  }
};
</script>

And in your App.vue, you listen for the event and call the method:

// App.vue
<template>
  <div id="app">
    <ChildComponent />
  </div>
</template>

<script>
import ChildComponent from '@/components/ChildComponent.vue';
import { eventBus } from './App.vue';

export default {
  components: {
    ChildComponent
  },
  created() {
    eventBus.$on('callMethod', () => {
      this.methodInApp(/* pass any arguments if needed */);
    });
  },
  methods: {
    methodInApp(/* args */) {
      // Your method logic here
    }
  }
};
</script>

2. Using Props:

If the method is simple and doesn’t need to be reused across many components, you can pass the method as a prop:

// App.vue
<template>
  <div id="app">
    <ChildComponent :methodInApp="methodInApp" />
  </div>
</template>

<script>
import ChildComponent from '@/components/ChildComponent.vue';

export default {
  components: {
    ChildComponent
  },
  methods: {
    methodInApp(/* args */) {
      // Your method logic here
    }
  }
};
</script>
// ChildComponent.vue
<script>
export default {
  props: ['methodInApp'],
  methods: {
    callMethodInApp() {
      this.methodInApp(/* pass any arguments if needed */);
    }
  }
};
</script>

3. Using Vuex:

If your application’s state management is handled by Vuex, you can define actions in Vuex and dispatch them from child components to call methods in App.vue.

This approach is suitable for larger applications with complex state management requirements.