SoFunction
Updated on 2025-04-04

Implement a method to call methods externally in vue (recommended)

1. First define a public vue component;

var eventHub = new Vue(); 

2. In the current component of the event, in created, use $on to pass to the public component eventHub, translate is customized, and getCardNum(data) is the method to be called externally;

eventHub.$on('translate', function (data) { 
        (data); 
      }); 

3. Finally, in the parent component, note that the negative component should be saved with a variable, var vm = new Vue({});

4. Define a method in the methods method in the parent component, and use $emit to receive the methods in the public component;

var vm = new Vue({ 
 el: '#example', 
 data: { 
  msg: 'Hello Directive', 
  data: {} 
 }, 
 methods: { 
  getCardNum: function (data, on) { 
   eventHub.$emit('translate', data); 
  } 
 } 
}); 

5. Finally, you can call the getCardNum (data) function outside the vue component or outside the file. For example, in html, you can call it onclick = () in this way; vm is the parent component

6. Be careful to write the variable name of the parent component on ();

During the process of using vue development, I encountered a pop-up page in the java background that wanted to call the methods in my vue component, but the pop-up page in the background is not in my vue component. The methods in the vue that other pages want to call can only be called in the parent component. So I studied it for a long time and finally decided to pass the function() method in the component to the parent component at the top layer, save the negative component in the variable, and finally call the method directly in other pages. When calling, I cannot use the @click method to call it, because the page in the background is not inside my vue component, so the call is onclick = (); in this way, vm is the parent component

The above method (recommended) to call methods externally in vue is all the content I share with you. I hope you can give you a reference and I hope you can support me more.