代码之家  ›  专栏  ›  技术社区  ›  jsonGPPD

事件函数内的数据对象不起作用,导致未定义

  •  -1
  • jsonGPPD  · 技术社区  · 8 年前

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

    以下是我的代码:

    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);});
              }
         }]
       }
    }
    

    我的警报结果是 undefined 但当我把我的警惕放在 this.eventSources = [{...]] 警报的值为 1

    我希望有人能帮助我。

    1 回复  |  直到 8 年前
        1
  •  2
  •   tony19 thanksd    8 年前

    问题是 this 里面 events() 实际上不是您的Vue实例。您可以通过声明 events 作为一个 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>