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 can assign a ref to our component and then we can call the component’s method with it.
For instance, we write
<template>
<my-component ref="foo"></my-component>
</template>
<script>
//...
export default {
//...
components: { "my-component": myComponent },
methods: {
doSomething() {
this.$refs.foo.doSomething();
},
},
//...
};
</script>
to assign the foo
ref to my-component
.
Then we call this.$refs.foo.doSomething();
in the doSomething
method where this.$refs.foo
references the my-component
component instance.
Conclusion
To call a Vue.js component method from outside the component, we can assign a ref to our component and then we can call the component’s method with it.