Call Vue Component Method from Outside the Component


In this short article, we will learn how to call a Vue component method from outside the component.

So, what we will do is, we will call a function (method) of a child component from its parent component.

First, let's create a child component with two simple methods.

Child component:

<template>
  <div class="hello">This is Child Component</div>
</template>

<script>
export default {
  name: "HelloWorld",
  methods: {
    greetUser() {
      console.log("Hello User");
    },
    byeUser() {
      console.log("Bye User");
    },
  },
};
</script>

In the child component HelloWorld.vue , we have created two methods:

greetUser() to console log "Hello User" and

byeUser() to console log "Bye User" in our terminal.

Now we will import this component to the parent component i.e App.vue.

So, to call the child component methods from outside the component, we will use the ref attribute in the parent component.

Parent component:

<template>
  <div id="app">
    <HelloWorld ref="hello" />
  </div>
</template>

The ref attribute is a special attribute that allows getting the direct reference to HTML elements or child elements in the template in VueJs.

Here we have referenced the child component as ref="hello".

Now, we will add two buttons Hello and Bye to call the methods in the child component using the ref attributes.

Full Code (Parent Component):

<template>
  <div id="app">
    <HelloWorld ref="hello" /> // Imported child component
    <button @click="helloFn()">Hello</button>
    <button @click="byeFn()">Bye</button>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld";

export default {
  name: "App",
  components: {
    HelloWorld,
  },
  methods: {
    helloFn() {
      this.$refs.hello.greet();
    },
    byeFn() {
      this.$refs.hello.bye();
    },
  },
};
</script>

When the hello button is clicked, it will run the helloFn() function which will call the greetUser() method in the child component.

And when the bye button is clicked, it will run the byeFn()to call the byeUser() method in the child component.

Demo :

And this is how you can access child component method in parent component.

Related Topics:

Update Parent Data From Child Component In VueJs

How To Call A Function In VUE Template?

How To Add Dynamic HTML Attributes In VueJS ?


💾 Recommended Articles