[Vuejs]-Vue: Push to array on event

2👍

It sounds to me like you’re misreading the problem. An arrow function binds its context, and the context of that arrow function is correctly bound to the other-component because it is within a method, and methods are auto-bound to their components. The below example works as expected.

const events = new Vue();

Vue.component('formComponent', {
  template: '<button @click="submitForm">Submit</button>',
  methods: {
    submitForm() {
      events.$emit('form-submitted', {
        foo: 1
      });
    }
  }
});

Vue.component('otherComponent', {
  template: '<div><div v-for="item in list">{{item}}</div></div>',
  data() {
    return {
      list: []
    }
  },
  mounted() {
    events.$on('form-submitted', data => {
      this.list.push(data);
    });
  }
});

new Vue({
  el: '#app'
});
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
  <form-component></form-component>
  <other-component></other-component>
</div>
👤Roy J

0👍

One solution would be to copy your this in a variable outside and use that to access the component’s data properties. For example, this should work:

import events from './events'
export default {
  ....
  mounted() {
    var that = this;
    events.$on('form-submitted, function(data) {
      that.list.push(data);
    )
  },
  data() {
    return {
      list: []
    }
  }
  ....
}
👤Gaurav

Leave a comment