Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js - How to call method from another component

I am using Vue.Js v2. I want to call component1->c1method in component2->c2method for reload data after submitting.

Vue.component('component1', {   methods: {     c1method: function(){      alert('this is c1method')     },   } }) Vue.component('component2', {   methods: {     c2method: function(){      component('component1').c1method()//like this     },   } }) 
like image 365
Miri Avatar asked Mar 24 '17 02:03

Miri


People also ask

How do you call a Vue method?

We can call a Vue. js method on page load by calling it in the beforeMount component hook. We can also make a method run on page load by calling it in the created hook. And we can do the same in the mounted hook.

How do you call parent method from child component in Vue?

To call parent method with component with Vue. js, we can get the parent component's method from the $parent property. to define the child component with Vue. component .


2 Answers

For non-parent-child relation, then this is the same as this one. Call one method, apparently any method of a component from any other component. Just add a $on function to the $root instance and call form any other component accessing the $root and calling $emit function.

On First component

     ....     mounted() {         this.$root.$on('component1', () => {             // your code goes here             this.c1method()         }     } 

and in the second component call the $emit function in $root

     ...     c2method: function(){      this.$root.$emit('component1') //like this     }, 

It acts more like a socket. Reference here

https://stackoverflow.com/a/50343039/6090215

like image 93
Mir Ayman Ali Avatar answered Sep 24 '22 09:09

Mir Ayman Ali


// Component A Vue.component('A', {     created() {         this.$root.$refs.A = this;     },     methods: {         foo: function() {             alert('this is A.foo');         }     } });  // Component B Vue.component('B', {     methods: {         bar: function() {             this.$root.$refs.A.foo();         }     } }); 
like image 35
Sajjad Shirazy Avatar answered Sep 24 '22 09:09

Sajjad Shirazy