Menu Close

How to call a Vue.js component method from outside the component?

How to call a Vue.js component method from outside the component?

In this article, we’ll look at how to call a Vue.js component method from outside the component.

To call a Vue.js component method from outside the component, we assign a ref to the component.

For instance, we write

<template>
  <div>
    <button @click="exec">Execute child component</button>
    <child-cmp ref="child" />
  </div>
</template>

<script>
export default {
  methods: {
    exec() {
      this.$refs.child.childMethod();
    },
  },
};
</script> 

to assign a ref to the child-cmp component.

Then we define the exec method that calls the childMethod in the this.$refs.child component, which is the child-cmp component since we assigned the ref to it.

Then we set the click handler of the button to exec to call it when we click on the button.

To call a Vue.js component method from outside the component, we assign a ref to the component.
Posted in Vue.js

You can also read...