【问题标题】:how do i loop through a json object from an api in vuejs?如何从 vuejs 中的 api 循环遍历 json 对象?
【发布时间】:2021-12-01 04:23:06
【问题描述】:

/亲爱的大家, 我想从这个 API 创建的 JSON 对象创建一个表,我如何在 Vue js 中使用 v-for? 设计并不重要,我只是在这种情况下无法实现 v-for?该表不应该只是一个平面html表/

<template>
  <div id="app">
    <table>
    <thead>
      <tr>
        <th>id</th>
        <th>meta</th>
        <th>title</th>
        <th>is private</th>

        </tr>
    </thead>
      
    </table>
  
  </div>

</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      items:''
    }
  },


  created() {
    axios.get(`https://zbeta2.mykuwaitnet.net/backend/en/api/v2/pages/`)
    .then(response => {
     
      this.items = response.data
    })
    
  }
}

</script>

<style>

</style>

【问题讨论】:

  • 你的response.data是一个对象数组吗?

标签: json vue.js


【解决方案1】:

您的 HTML 表格:

<table>
      <thead>
        <tr>
          <th>id</th>
          <th>meta</th>
          <th>title</th>
          <th>is private</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in items" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.meta.detail_url }}</td>
          <td>{{ item.title }}</td>
          <td>{{ item.is_private }}</td>
        </tr>
      </tbody>
    </table>

脚本:

async created() {
    const response = await axios.get(
      `https://zbeta2.mykuwaitnet.net/backend/en/api/v2/pages/`
    );
    this.items = response.data.items;
  },

【讨论】:

  • 感谢 babis95,但在此之后我的桌子是空的 :(,它对你有用吗?
  • 请查看编辑后的代码。更改了 HTML 以反映 API 数据密钥。将您的脚本更改为使用异步等待(我的偏好)...您可以继续使用承诺,它也会起作用
  • 非常感谢 babis95
  • babis95,如何从多页 api 中获取包含该代码的 json 数据?像这样:zbeta2.mykuwaitnet.net/backend/en/api/v2/media-center/…,谢谢你的麻烦
猜你喜欢
  • 1970-01-01
  • 2021-10-07
  • 2015-09-16
  • 1970-01-01
  • 2023-03-07
  • 2016-11-18
  • 2021-07-03
  • 2021-06-16
相关资源
最近更新 更多