[Vuejs]-Vue Call another component file method

0👍

You can implement a custom event to call functions in between components. I have illustrated two method that you can use to bind event and call functions.

Method 1


Keep separate instance of the Vue, only to register custom event. assign it to window so that it can be accessed from eveywhere

// Initiate
window.Notifier = new Vue();

// Bind event
window.Notifier.$on('regenPieChartMethod1', function(message){
    //code block
});

// Call event from any component
window.Notifier.$emit('regenPieChartMethod1', message);

Method 2


Bind event to the parent component, so that it can be accessed from child components

// Bind event
this.$parent.$on('regenPieChartMethod2', function(message){
    //code block
});

// Call event from child component
this.$parent.$emit('regenPieChartMethod2', message);

You can use whichever option suits for your implementation

Full Solution

// Use a seperate Vue instance only for event
window.Notifier = new Vue();

Vue.component('dashboard', {
  methods: {
  
    callRegenPieChartMethod1 () {
    
      var message = 'Pie Chart data is regenerated using method 1';
        window.Notifier.$emit('regenPieChartMethod1', message);
    },
    
    callRegenPieChartMethod2 () {
    
      var message = 'Pie Chart data is regenerated using method 2';
      this.$parent.$emit('regenPieChartMethod2', message);
    }
  },
  template: '<div><h4>Dashboard Component</h4><button @click="callRegenPieChartMethod1">Refresh Pie Chart - Method 1</button> <button @click="callRegenPieChartMethod2">Refresh Pie Chart - Method 2</button></div>',
});


Vue.component('piechart', {
  data() {
    return {
      message: 'This is initial data of the pie chart!'
    };
  },
  mounted() {
    var _t = this;
    
    // use seperate Vue instance to bind event
    window.Notifier.$on('regenPieChartMethod1', function(message){
        _t.genChart(message);
    });
    
    // bind event to the parent
    this.$parent.$on('regenPieChartMethod2', function(message){
        _t.genChart(message);
    });
  },
  methods: {
    genChart (message) {
      this.message = message;
    }
  },
  template: '<div><h4>Pie Chart Component</h4> <p>Message : {{message}}</p></div>',
});

new Vue({
  el: '#app',
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <dashboard></dashboard>
  <piechart></piechart>
</div>

Leave a comment