Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue best practice for calling a method in a child component

Tags:

vue.js

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!

like image 295
user1525612 Avatar asked Mar 23 '19 17:03

user1525612


People also ask

How do you call a function on a child component on parent events?

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.

How do you call a Vue method?

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.


1 Answers

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.

like image 131
Flame Avatar answered Sep 20 '22 19:09

Flame