2017-05-14 36 views
2

我正在嘗試使用created生命週期掛鉤在我的組件上設置數據屬性。以下是我的單文件組件。運行此代碼時,我正在控制檯中看到"TypeError: Cannot read property 'summary' of undefined"。這告訴我該模板正在使用forecastData作爲data屬性中聲明的空對象,而不是來自created的已填充對象。當我完全刪除data財產時,我看到TypeError: Cannot read property 'currently' of undefined。顯然,我在這裏錯過了一些基本的東西。如何在VueJS生命週期鉤子內設置數據

<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> 

回答

2

您正在異步設置數據,因此在第一次安裝對象時它不存在。當您嘗試訪問forecastData.currently.summary時,currently屬性未定義,導致您的錯誤。使用v-if來避免錯誤。

<h2 v-if="forecastData.currently">{{forecastData.currently.summary}}</h2> 

或者,在您的初始化中定義空值彙總。

data() { 
    return { 
    forecastData: { 
     summary: null 
    } 
    } 
}, 
+0

謝謝!已更新爲'forecastData:{currently:{summary:null}}',它可以工作。這是在創建組件時異步獲取和設置數據的正確方法嗎? – MattDionis

+1

@MattDionis你正在做的事情非常好,你只需要注意組件最初安裝時可能不存在的嵌套屬性。 – Bert