Search code examples
javascriptvue.jseventscomponentsemit

VueJs SPA execute function on click button


I need to run refreshMailList function from mail-list tag catching the click event from mail-list component.

I have this vue instance with this component:

Vue.component('mail-list', {
  props: ['inboxmail'],
  template:
  `
  <div>
    <h4>{{inboxmail}}</h4>
    <button>Refresh</button>
  </div>
  `
  });


//Creating the Vue object.
let options = {
  el: "#app",
  data: {
    pollingId: null,
    inbox: ''
  },

  created: function() {
    this.refreshMailList()
  },
methods:{
    refreshMailList: function(){
      fetch('/inbox')
      .then(response => response.json())
      .then(aJson => {
        this.inbox = aJson;
      })
    },

  } //end methods
} //end options

//ViewModel (vm)
let vm = new Vue(options);

And I have this index.html:

      <div id="app">
        <mail-list v-bind:inboxmail="inbox" @refresh='refreshMailList'></mail-list>
      </div>

Solution

  • You need to emit the event from inside the mail-list component.

    Try this snippet:

     Vue.component('mail-list', {
      props: ['inboxmail'],
      methods: {
        refresh: function() {
          this.$emit('refresh');
        },
      },
      template:
      `
      <div>
        <h4>{{inboxmail}}</h4>
        <button @click="refresh">Refresh</button>
      </div>
      `
      });