No need for complicated workarounds.
Vue.js allows us to create events that can be listened to globally.
This means that whenever we want to invoke a specific function, all we have to do is emit this event.
Then, we simply listen for this event within the component and execute the desired method when it occurs.
It's as straightforward as this:
- To implement this feature, navigate to main.js and add the following line before creating the Vue instance:
export const eventBus = new Vue(); // added line
new Vue({
...
...
...
render: h => h(App)
}).$mount('#app');
- Instead of directly calling the target function, emit the specified event wherever necessary:
eventBus.$emit('fireMethod');
- In the component containing the target function, always listen for this global event:
created() {
eventBus.$on('fireMethod', () => {
this.myBelovedMethod();
})
}
And don't forget to import eventBus at the top of your file.
import {eventBus} from "path/to/main.js";
That's all there is to it - just a few lines of clean code harnessing the power of Vue.js.