Call a Vue.js component method from outside the component

In the end I opted for using Vue’s ref directive. This allows a component to be referenced from the parent for direct access.

E.g.

Have a component registered on my parent instance:

var vm = new Vue({
    el: '#app',
    components: { 'my-component': myComponent }
});

Render the component in template/html with a reference:

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

Now, elsewhere I can access the component externally

<script>
vm.$refs.foo.doSomething(); //assuming my component has a doSomething() method
</script>

See this fiddle for an example: https://jsfiddle.net/0zefx8o6/

(old example using Vue 1: https://jsfiddle.net/6v7y6msr/)

Edit for Vue3 – Composition API

The child-component has to return the function in setup you want to use in the parent-component otherwise the function is not available to the parent.

Note: <sript setup> doc is not affacted, because it provides all the functions and variables to the template by default.

Leave a Comment