I have been reading lots of articles about this, and it seems that there are multiple ways to do this with many authors advising against some implementations.
To make this simple I have created a really simple version of what I would like to achieve.
I have a parent Vue, parent.vue. It has a button:
<template> <div> <button v-on:click="XXXXX call method in child XXXX">Say Hello</button> </div> </template>
In the child Vue, child.vue I have a method with a function:
methods: { sayHello() { alert('hello'); } }
I would like to call the sayHello()
function when I click the button in the parent.
I am looking for the best practice way to do this. Suggestions I have seen include Event Bus, and Child Component Refs and props, etc.
What would be the simplest way to just execute the function in my method?
Apologies, this does seem extremely simple, but I have really tried to do some research.
Thanks!
To call function on child component on parent events with Vue. js, we can assign the ref to the child component and then call the method in the parent when the event is emitted. to add a template with the child-component added. We assign a ref to it.
We can call a Vue. js method on page load by calling it in the beforeMount component hook. We can also make a method run on page load by calling it in the created hook. And we can do the same in the mounted hook.
One easy way is to do this:
<!-- parent.vue --> <template> <button @click="$refs.myChild.sayHello()">Click me</button> <child-component ref="myChild" /> </template>
Simply create a ref
for the child component, and you will be able to call the methods, and access all the data it has.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With