JavaScriptVue js
VueJs – How to call a method from non-parent-child component in vue-js
If you have an idea about the vue js then you know that how we can pass variables or methods in Vue js , basically we use the props to do such activity, but what if there is no parent-child relation in the component, and you can want to call those methods.
You can also read: How to pass value to child component in Vue.js
Let’s suppose I have two components, one name is ComponentOne.vue and another as ComponentTwo.vue, and I want to call componentOne.vue method from ComponentTwo.vue.
ComponentOne.vue Code
created() {
//at the place of componentOne you can write your component name
this.$root.$refs.ComponentOne = this
}
methods: {
test() {
console.log('Hello Codehunger')
}
}
ComponentTwo.vue Code
this.$root.$refs.ComponentOne.test()
That’s it this is how you can call a component method when there is no parent-child relation