Programing

VueJS 라이프사이클 후크 내에서 데이터를 설정하는 방법

c10106 2022. 3. 25. 20:58
반응형

VueJS 라이프사이클 후크 내에서 데이터를 설정하는 방법

I am trying to use the which. I tryingcreated구성 요소에 데이터 속성을 설정하는 라이프사이클 후크.아래는 나의 단일 파일 컴포넌트다.나는 지금 만나고 있다."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.summarycurrently속성이 정의되지 않아 오류가 발생함

사용 av-if실수를 피하기 위해

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

또는 초기화에 null 요약을 정의하십시오.

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

참조URL: https://stackoverflow.com/questions/43967940/how-to-set-data-within-vuejs-lifecycle-hook

반응형