简体   繁体   English

Vue.js API提取

[英]Vue.js API fetching

I'm a student, and I'm just starting to use Vue. 我是学生,刚开始使用Vue。 I'm making this app that displays train information, but it's not showing any data when I fetch the items from the API. 我正在制作这个显示火车信息的应用程序,但是当我从API提取商品时它没有显示任何数据。 It's also not giving any errors in the console. 在控制台中也没有出现任何错误。

main.js: 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: 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: API:

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

Screenshot of my network tab: 我的网络标签的屏幕截图:

在此处输入图片说明

Your API returns an object that looks like this: 您的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"
}

I think you actually want to iterate over the items property of the object, in which case your v-for should be: 我认为您实际上想遍历对象的items属性,在这种情况下,您的v-for应该是:

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

Alternatively, if you wanted treinen to contain only the original items array, you could destructure the items property in the last arrow-function: 另外,如果你想treinen只包含原items数组,你可以解构items在最后一箭功能特性:

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

Now, your original v-for (in <div v-for="(trein, i) in treinen"> ) would work as-is because treinen contains the intended items. 现在,您的原始v-for (在<div v-for="(trein, i) in treinen"> )将按原样工作,因为treinen包含了预期的项目。

demo 演示

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

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