2016-12-04 145 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

我希望我能调整从组件的生命周期这种行为,它的工作 –