Data object inside the event function doesn't

2019-09-20 10:30发布

问题:

I'm having an undefined value when I put my object data inside the event.

Here are my codes:

data(){
    return {
       eventSources: [],
       myId: 1
    }
},
methods:{
   myMethod(){
     this.eventSources = [{
          events(start,end,timezone,callback){
              alert(this.myId); 
              axios.get(`/Something?id=${this.myId}`).then(response=>{
                  callback(response.data);
              }).catch(error=>{console.log(error);});
          }
     }]
   }
}

My alert is resulted to undefined but when I put my alert above the this.eventSources = [{...]] the alert has a value of 1

I hope somebody helps me.

回答1:

The problem is this inside events() is not actually your Vue instance. You can fix the context by declaring events as an arrow-function:

this.eventSources = [{
  events: (start,end,timezone,callback) => {
    alert(this.myId);
  }
}]

new Vue({
  el: '#app',
  data() {
    return {
      eventSources: [],
      myId: 1
    };
  },
  methods: {
    myMethod() {
      this.eventSources = [{
        events: (start,end,timezone,callback) => {
          alert(this.myId);
        }
      }]

      this.eventSources[0].events(0, 1, 'UTC', data => console.log(data))
    }
  }
})
<script src="https://unpkg.com/vue@2.5.16"></script>

<div id="app">
  <button @click="myMethod">Click</button>
</div>