事件函数内的数据对象不起作用并导致未定义 [英] Data object inside the event function doesn't work and resulted to undefined

查看:15
本文介绍了事件函数内的数据对象不起作用并导致未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将对象数据放入事件时,我有一个未定义的值.

这是我的代码:

data(){返回 {事件来源:[],我的 ID:1}},方法:{我的方法(){this.eventSources = [{事件(开始,结束,时区,回调){警报(this.myId);axios.get(`/Something?id=${this.myId}`).then(response=>{回调(响应数据);}).catch(error=>{console.log(error);});}}]}}

我的警报结果为 undefined 但是当我将警报置于 this.eventSources = [{...]] 上方时,警报的值为 1

希望有人能帮助我.

解决方案

问题在于 events() 中的 this 实际上并不是你的 Vue 实例.您可以通过将 events 声明为 箭头功能:

this.eventSources = [{事件:(开始,结束,时区,回调)=>{警报(this.myId);}}]

new Vue({el: '#app',数据() {返回 {事件来源:[],我的 ID:1};},方法: {我的方法(){this.eventSources = [{事件:(开始,结束,时区,回调)=>{警报(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="应用程序"><button @click="myMethod">点击</button>

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.

解决方案

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>

这篇关于事件函数内的数据对象不起作用并导致未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆