I am attempting to use the created
lifecycle hook to set a data property on my ponent. Below is my single-file ponent. I'm currently seeing "TypeError: Cannot read property 'summary' of undefined"
in the console when running this code. This tells me that the template is working with forecastData
as the empty object declared in the data
property rather than the populated object from created
. When I remove the data
property entirely I see TypeError: Cannot read property 'currently' of undefined
. Clearly, I'm missing something basic here.
<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>
I am attempting to use the created
lifecycle hook to set a data property on my ponent. Below is my single-file ponent. I'm currently seeing "TypeError: Cannot read property 'summary' of undefined"
in the console when running this code. This tells me that the template is working with forecastData
as the empty object declared in the data
property rather than the populated object from created
. When I remove the data
property entirely I see TypeError: Cannot read property 'currently' of undefined
. Clearly, I'm missing something basic here.
<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>
Share
Improve this question
asked May 14, 2017 at 19:21
MattDionisMattDionis
3,62610 gold badges55 silver badges110 bronze badges
1 Answer
Reset to default 4You are setting the data asynchronously so it doesn't exist when the object is first mounted. When you try to access forecastData.currently.summary
the currently
property is undefined, which results in your error.
Use a v-if
to avoid the error.
<h2 v-if="forecastData.currently">{{forecastData.currently.summary}}</h2>
Alternatively, define a null summary in your initialization.
data () {
return {
forecastData: {
summary: null
}
}
},
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744898229a4599824.html
评论列表(0条)