如何在 VueJS 生命周期钩子中设置数据

How to set data within VueJS lifecycle hook

我正在尝试使用 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>

您正在异步设置数据,因此当对象首次装载时它不存在。当您尝试访问 forecastData.currently.summary 时,currently 属性 未定义,这会导致您出错。

使用 v-if 避免错误。

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

或者,在您的初始化中定义一个空摘要。

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