Categories
Vue Answers

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

Spread the love

Sometimes, we want 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.

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.

Conclusion

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *