IT이야기

Vue JS가 반환된 메서드 데이터를 DOM에 표시할 수 없음

cyworld 2022. 3. 16. 22:04
반응형

Vue JS가 반환된 메서드 데이터를 DOM에 표시할 수 없음

템플릿 html

<div class="item" v-for="n, index in teamRoster">
   <span> {{ getFantasyScore(n.personId) }} </span>
</div>

방법

getFantasyScore(playerId) {
    if(playerId) {
        axios.get(config.NBLAPI + config.API.PLAYERFANTASYSCORE + playerId)
        .then( (response) => {
            if( response.status == 200 ) {
                console.log(response.data.total)
                return response.data.total;
            }
        });
    }
}

반환된 데이터를 DOM에 표시하려고 하는데 아무것도 표시되지 않아.하지만 내가 로그를 위로하려고 하면 데이터가 표시된다.어떻게 하면 진열할 수 있을까.제가 무엇을 빠뜨리고 있나요?

문제는, 당신의getFantasyScore방법은 아무 것도 반환하지 않고, 심지어 데이터는 비동기적이며 반응적이지 않다.

생성 시 데이터를 로드하는 구성 요소를 만들 것이다.뭐랄까

Vue.component('fantasy-score', {
  template: '<span>{{score}}</span>',
  props: ['playerId'],
  data () {
    return { score: null }
  },
  created () {
    axios.get(config.NBLAPI + config.API.PLAYERFANTASYSCORE + this.playerId)
      .then(response => {
        this.score = response.data.total
      })
  }
})

그리고 네 템플릿에서

<div class="item" v-for="n, index in teamRoster">
  <fantasy-score :player-id="n.personId"></fantasy-score>
</div>

AJAX 결과는 비동기적이므로 메소드를 사용하면 안 된다.당신은 모든 것을 되찾을 수 있다.teamRoster그리고 나서 이것을 당신의 것에 추가하십시오.div:

<div class="item" v-for="fantasyScore in teamRoster" v-if="teamRoster">
   <span> {{ fantasyScore }} </span>
</div>

참조URL: https://stackoverflow.com/questions/45450998/vue-js-unable-to-display-to-dom-the-returned-data-of-method

반응형