Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

vue.js - Vue best practice for calling a method in a child component

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...