【问题标题】:Vue JS unable to display to DOM the returned data of methodVue JS 无法向 DOM 显示方法返回的数据
【发布时间】:2018-01-09 02:21:38
【问题描述】:

模板 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,但它没有显示任何内容。但是当我尝试控制台日志时,数据就会显示出来。我怎样才能显示它。我错过了什么?

【问题讨论】:

  • 如何填充teamRoster 对象/数组?同时预取幻想分数数据可能更容易

标签: javascript vue.js frontend vuejs2 vue-component


【解决方案1】:

您不应该对 AJAX 结果使用方法,因为它们是异步的。您可以检索完整的 teamRoster 对象,然后将其添加到您的 div

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

【讨论】:

  • getFantasyScoreByPerson 是在哪里调用的,id 是如何传递给它的?
  • @Phil,解决了这个问题!
  • 并非如此。 this.id 来自哪里?它是如何从转发器中的n.personId 得到id 的?
  • 我简化了它。没有仔细阅读要求。就像您首选的解决方案一样,@Phil。
【解决方案2】:

问题是,您的 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>

【讨论】:

    猜你喜欢
    • 2017-11-30
    • 2019-07-22
    • 2021-02-21
    • 2019-03-27
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    相关资源
    最近更新 更多