gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:49:59 25 4
gpt4 key购买 nike

我有一个功能性的代码片段,在这里列出了歌曲列表: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]:“数据”选项应该是一个函数,它返回组件定义中的每个实例值。 另一个告诉我 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()
}
}
})

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

最佳答案

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

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

第二:在函数fetchData中, 在您分配给 xhr.onload 的函数中,可能是 this指的是xhr xhr.onload 时的对象执行。

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

关于javascript - 如何使用 Vue.js 在组件模板中循环遍历 JSON/API 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39525979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com