2016-12-04 268 views
0

雖然與vue.js玩弄我注意到在試圖顯示從一個API頁面的數據,但在這裏是很奇怪的一些奇怪的行爲:Vue公司和REST API數據

  • 使用VUE 2.0.0 ,我可以看到「標題」,但我有一個錯誤在開發控制檯[見printscreen]
  • 使用最新的vue版本,我看不到「標題」[和我在打印屏幕上有同樣的錯誤]

這是正常的嗎?

的源代碼:

template: 
    '<div>'+ 
     'Form with id = {{id}}'+ 
     '<br/>'+ 
     'has title = {{item.details.Title}}'+ 
    '</div>', 
    data: function(){ 
    return { 
     id: '', 
     item: {} 
    } 
    }, 
    created: function() { 
    this.get() 
    }, 
    methods: { 
    get: function() { 
     var self = this 
     id = window.location.hash 
     id = id.replace('#/whatever/','') 
     axiosInstance.get('/thebackendresource/'+id) // <--- make http calls etc 
     .then(function (response) { 
      self.id = id 
      self.item = response.data 
      console.log(self.item) 
     }).catch(function (error) { 
      console.log(error) 
     } 
    ); 
    } 
    } 

This is the case when vue 2.0.0 is used

回答

2

您收到此錯誤,因爲當你從axiosinstance獲取數據,那個時候item.details是空的,當它試圖使其拋出這個錯誤。

api調用完成後,它會更新DOM並重新呈現DOM,因此您可以看到item.details.Title呈現。

您需要添加一個空檢查,以防止出現此錯誤,可使用v-if輕鬆完成,就像follwoing:

template: 
'<div>'+ 
    'Form with id = {{id}}'+ 
    '<br/>'+ 
    '<span v-if="item.details"> has title = {{item.details.Title}}'+ 
    '</span>' + 
'</div>', 
+0

我希望我能調整從組件的生命週期這種行爲,它的工作 –