我正在尝试使用created
生命周期钩子在我的组件上设置数据属性。下面是我的单文件组件。我正在运行此代码时在控制台中看到"TypeError: Cannot read property 'summary' of undefined"
。这告诉我模板正在使用forecastData
作为data
属性中声明的空对象,而不是来自created
的填充对象。当我完全删除data
属性时,我会看到TypeError: Cannot read property 'currently' of undefined
。显然,我在这里缺少一些基本的东西。
<template>
<div>
<p>
<router-link to="/">Back to places</router-link>
</p>
<h2>{{forecastData.currently.summary}}</h2>
<router-link :to="{ name: 'forecast' }">Forecast</router-link>
<router-link :to="{ name: 'alerts' }">Alerts</router-link>
<hr>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'CurrentWeather',
data () {
return {
forecastData: {}
}
},
created: function () {
this.$http.get('/api/forecast/boston').then((response) => {
this.forecastData = response.data;
}, (err) => {
console.log(err)
});
}
}
</script>
<style scoped>
</style>
答案 0 :(得分:4)
您正在异步设置数据,因此在首次装入对象时它不存在。当您尝试访问forecastData.currently.summary
时,currently
属性未定义,这会导致您的错误。
使用v-if
来避免错误。
<h2 v-if="forecastData.currently">{{forecastData.currently.summary}}</h2>
或者,在初始化中定义一个空摘要。
data () {
return {
forecastData: {
summary: null
}
}
},