How to Call a Vue.js Component Method From Outside The Component

In this tutorial, we will discuss the cleanest way of calling a Vue.js component method from outside the component. Let’s see if there is a nice way to call a method that belongs to one of these components from outside the Vue instance.

You can set ref for child components, after that call in parent via $refs.

Add ref to the child component like this:

<my-component ref="childref"></my-component>

Add click event to the parent like this:

<button id="external-button" @click="$refs.childref.increaseCount()">External Button</button>

Here is the full example:

<!DOCTYPE html>
<html>
  <head>
    <title>How to Call a Vue.js Component Method From Outside The</title>
  </head>
  <body>
    <div id="app">
      <my-component ref="childref"></my-component>
      <button id="external-button" @click="$refs.childref.increaseCount()">External Button</button>
    </div>
    <template id="my-template">
      <div style="border: 1px solid; padding: 2px;" ref="childref">
        <p>A counter: {{ count }}</p>
        <button @click="increaseCount">Internal Button</button>
      </div>
    </template>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <script>
      new Vue({
        el: '#app',
        components: {
          'my-component': {
            template: '#my-template',
            data: function() {
              return {
                count: 0,
              };
            },
            methods: {
              increaseCount: function() {
                this.count++;
              }
            }
          },
        }
      });
    </script>
  </body>
</html>

Vue components are reusable instances with a name, so that is why they accept the same options as new Vue, data, computed, watch, methods. The exceptions are some root-specific options such as el.


Do you find this helpful?

Related articles