2016-08-26 53 views
1

我試圖在ready()方法中收到響應時,設置一個名爲types的數據對象。Vue.js奇怪的錯誤

像這樣:

export default { 

    data() { 
    return { 
     types: null 
    } 
    }, 

    ready() { 
    TypeService.showAll(1) 
     .then(function(data) { 
      this.types = data.types 
     }); 
    } 
} 

但我收到以下錯誤控制檯:

Cannot set property 'types' of undefined(…) 

但是,當我CONSOLE.LOG這樣的:

ready() { 
    TypeService.showAll(1) 
     .then(function(data) { 
      console.log(data); 
     }); 
    } 

這不是空!?!?

enter image description here

這到底是怎麼回事?它讓我瘋狂。

- 編輯 -

TypeService.showAll(1) 
     .then(({ data }) => ({ 
      this.types: data.types 
      }.bind(this))); 

回答

3

問題是this.types,不data.types(其中JS錯誤報文不會使完全清楚)。

ready() { 
    TypeService.showAll(1) 
     .then(function(data) { 
      this.types = data.types 
     }); 
    } 

this是不是你在這裏function中期待什麼(它不是Vue的成分)。這應該是訣竅:

ready() { 
    TypeService.showAll(1) 
     .then(function(data) { 
      this.types = data.types 
     }.bind(this)); 
    } 
+0

@Jamie我不確定。新的ES6語法不是我已經完全採用的。 – ceejayoz

+1

好的,謝謝你的幫助。 – Jamie

2

嘗試

ready() { 
var _this = this 
TypeService.showAll(1) 
    .then(function(data) { 
     _this.types = data.types 
    }); 
}