简体   繁体   English

如何使用Vue.js在组件模板中循环遍历JSON / API数据

[英]How to loop through JSON/API data inside a component template with Vue.js

I've got a functioning snippet rending a list of songs here: https://jsfiddle.net/jeremypbeasley/guraav4r/8/ 我有一个运行良好的代码片段,在此处整理了歌曲列表: 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: HTML:

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

The problem is that when I attempt to use this same general method in the context of a component, it breaks and logs two errors: 问题是,当我尝试在组件的上下文中使用相同的通用方法时,它会中断并记录两个错误:

First: [Vue warn]: The "data" option should be a function that returns a per-instance value in component definitions. 首先: [Vue warn]: The "data" option should be a function that returns a per-instance value in component definitions. and another telling me that commits.toptracks is undefined. 另一个告诉我commits.toptracks是未定义的。

My failed attempt: 我失败的尝试:

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()
    }
  }
})

Any help making sense of these errors and helping me understand what I'm doing wrong would be much appreciated! 能够帮助您理解这些错误并帮助我了解我在做错什么的任何帮助将不胜感激!

First: You define the data property as an object literal, instead you should use a function that returns an object literal when executed. 第一:将data属性定义为对象文字,而应使用一个在执行时返回对象文字的函数。 For example: 例如:

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

Second: In the function fetchData , in the function you assign to xhr.onload , it may be that this refers to the xhr object when xhr.onload executes. 第二:在功能fetchData ,在分配给功能xhr.onload ,这可能是因为this是指xhr对象时xhr.onload执行。

Side note: You might want to look up vue-resource , it's more convenient than using XMLHttpRequest. 旁注:您可能想查找vue-resource ,这比使用XMLHttpRequest更为方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM