gpt4 book ai didi

javascript - Vue.js API 获取

转载 作者:行者123 更新时间:2023-12-03 00:51:03 25 4
gpt4 key购买 nike

我是一名学生,刚刚开始使用 Vue。我正在制作这个显示火车信息的应用程序,但当我从 API 获取项目时,它没有显示任何数据。它也没有在控制台中给出任何错误。

main.js:

new Vue({
el: "#app",
data: {
treinen: []
},
mounted() {
fetch("https://api.myjson.com/bins/owxas")
.then(response => response.json())
.then((items) => {
this.treinen = items;
})
},
template: `
<div class="flex">
<div v-for="trein, i in treinen">
<h1>{{ trein.title }}</h1>
</div>
</div>
`,
});

HTML:

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet"

href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<title>treinen</title>
<style>

</style>
</head>

<body>
<h1>treinen</h1>

<div id="app"></div>

<script src="https://unpkg.com/vue"></script>
<script src="main.js"></script>
</body>

</html>

API:

https://api.myjson.com/bins/owxas

我的网络选项卡的屏幕截图:

enter image description here

最佳答案

您的 API 返回一个如下所示的对象:

{
description: "Feed met alle treinstoringen en werkzaamheden op het Nederlandse spoornet."
home_page_url: "https://www.rijdendetreinen.nl/"
items: [{
id: "disruption-24194-nl",
title: "Amsterdam-Gouda: werkzaamheden elders",

}, …]
title: "Rijden de Treinen"
version: "https://jsonfeed.org/version/1"
}

我认为您实际上想迭代 items对象的属性,在这种情况下你的 v-for应该是:

<div v-for="(trein, i) in treinen.items">

或者,如果您想要 treinen仅包含原始 items数组,你可以 destructure items最后一个箭头函数中的属性:

fetch(...)
.then(response => response.json())
.then(({ items }) => { // <-- destructuring items
this.treinen = items;
});

现在,你原来的v-for (在 <div v-for="(trein, i) in treinen"> 中)将按原样工作,因为 treinen包含预期的项目。

demo

关于javascript - Vue.js API 获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53041075/

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