Sometimes, we may want to call a Vue 3 component method from outside the component.
In this article, we’ll look at how to call a Vue 3 component method from outside the component.
Assign a Ref to the Component and Call the Method From it
We can assign a ref to a component and get the method from the ref object and call it.
For instance, we can write:
App.vue
<template>
<HelloWorld ref="helloWorld" />
<button @click="greet">greet</button>
</template>
<script>
import HelloWorld from "./components/HelloWorld";
export default {
name: "App",
components: {
HelloWorld,
},
methods: {
greet() {
this.$refs.helloWorld.greet("jane");
},
},
};
</script>
components/HelloWorld.vue
<template>
<div>hello world</div>
</template>
<script>
export default {
methods: {
greet(name) {
console.log(`hello world ${name}`);
},
},
};
</script>
We assign the helloWorld
ref to the HelloWorld
component.
Then we add the greet
method that calls this.$refs.helloWorld.greet
method which is the greet
method from the HelloWorld
component.
Therefore, we should see the 'hello world jane'
logged when we click the greet button.
This lets us call a method in the child component from the parent.
Send an Event from the Child Component to the Parent
If we want to call a method in the parent component from the child component, then we should call the $emit
method from the child component and listen to the event emitted by the child component in the parent component.
For instance, we can write:
App.vue
<template>
<HelloWorld @greet="greet" />
</template>
<script>
import HelloWorld from "./components/HelloWorld";
export default {
name: "App",
components: {
HelloWorld,
},
methods: {
greet(name) {
console.log(`hello world ${name}`);
},
},
};
</script>
components/HelloWorld.vue
<template>
<div>hello world</div>
<button @click="greet">greet</button>
</template>
<script>
export default {
methods: {
greet() {
this.$emit("greet", "jane");
},
},
};
</script>
In HelloWorld.vue
, we have the greet
method which calls this.$emit
with the event name as the first argument and the event payload as the 2nd argument.
Subsequent arguments are also event payloads which will be used as 2nd and subsequent arguments of the event handler method.
Then in App.vue
, listen to the greet
event with the @greet
directive.
We set its value to greet
to get the value we passed in as the 2nd argument.
So name
is 'jane'
.
And we should see 'hello world jane'
logged when we click the greet button.
Conclusion
To call methods in a child component from the parent, we assign a ref to the component and get its methods from there.
If we want to call a method in the parent component from the child, then we emit an event in the child component and listen to that event in the parent component.