【问题标题】:How to loop through JSON/API data inside a component template with Vue.js如何使用 Vue.js 在组件模板中循环访问 JSON/API 数据
【发布时间】:2017-01-24 08:35:01
【问题描述】:

我有一个功能正常的 sn-p,可以在此处提供歌曲列表:https://jsfiddle.net/jeremypbeasley/guraav4r/8/

var apiURL = "https://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user=thisisheroic&period=7day&limit=6&api_key=3cbc1a3aa903935d08223263bcc3ba0b&format=json";

new Vue({
  el: '#demo',
  data: {
    commits: null
  },
  created: function () {
    this.fetchData()
  },
  methods: {
    fetchData: function () {
      var xhr = new XMLHttpRequest()
      var self = this
      xhr.open('GET', apiURL)
      xhr.onload = function () {
        self.commits = JSON.parse(xhr.responseText)
      }
      xhr.send()
    }
  }
})

html:

<div id="demo">
  <h1>Tracks</h1>
  <li v-for="mytrack in commits.toptracks.track">
      {{mytrack.name}}
  </li>
</div>

问题是,当我尝试在组件的上下文中使用相同的通用方法时,它会中断并记录两个错误:

首先:[Vue warn]: The "data" option should be a function that returns a per-instance value in component definitions.,另一个告诉我 commits.toptracks 未定义。

我的失败尝试:

Vue.component('manage-posts', {
  template: '#manage-template',
  data: {
    commits: null,
  },
  created: function () {
    this.fetchData()
  },
  methods: {
    fetchData: function () {
      var xhr = new XMLHttpRequest()
      xhr.open('GET', apiURL)
      xhr.onload = function () {
        this.data = JSON.parse(xhr.responseText);
        console.log(JSON.parse(xhr.responseText));
      }
      xhr.send()
    }
  }
})

任何帮助理解这些错误并帮助我理解我做错了什么将不胜感激!

【问题讨论】:

    标签: javascript json vue.js


    【解决方案1】:

    首先:您将 data 属性定义为对象字面量,而应使用在执行时返回对象字面量的函数。例如:

    ...
    data: () => ({
        commits: null
    }),
    ...
    

    第二:在fetchData函数中,在你赋给xhr.onload的函数中,可能thisxhr.onload执行时引用了xhr对象。

    附注:您可能想查找vue-resource,它比使用 XMLHttpRequest 更方便。

    【讨论】:

      猜你喜欢
      • 2019-06-19
      • 1970-01-01
      • 2019-10-09
      • 1970-01-01
      • 2019-07-04
      • 2018-10-14
      • 2021-05-10
      • 1970-01-01
      • 2023-04-09
      相关资源
      最近更新 更多